Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android setAdapter上的Json空指针_Android_Json - Fatal编程技术网

Android setAdapter上的Json空指针

Android setAdapter上的Json空指针,android,json,Android,Json,我是android新手。我在执行GetData时遇到NullPointerException 类,该类是正确的。 我认为问题在于错误的url或获取数据的类型。 JSON文件: 带变量的已编辑代码 private ListView lv; private ArrayList<HashMap<String, String>> newslist; @Override protected void onCreate(Bundle savedInstanceState) {

我是android新手。我在执行GetData时遇到NullPointerException 类,该类是正确的。 我认为问题在于错误的url或获取数据的类型。 JSON文件:

带变量的已编辑代码

private ListView lv;
private ArrayList<HashMap<String, String>> newslist;

@Override
protected void  onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
...
newslist = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_cat1);

    new GetData().execute();
}

private class GetData extends AsyncTask<Void, Void, Void> {
   ...
    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String url = "http://legs-legs.ru/cat1json.php?json=cat1";
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                JSONArray contacts = jsonObj.getJSONArray("cat1");

                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);
                    String id = c.getString("id");
                    String title_cat1 = c.getString("title_cat1");
                    String fulltext_cat1 = c.getString("fulltext_cat1");

                    // tmp hash map for single contact
                    HashMap<String, String> news_item = new HashMap<>();

                    // adding each child node to HashMap key => value
                    news_item.put("id", id);
                    news_item.put("title_cat1", title_cat1);
                    news_item.put("fulltext_cat1", fulltext_cat1);
                    //contact.put("mobile", mobile);

                    // adding contact to contact list
                    newslist.add(news_item);
                }
            } catch (final JSONException e) {...

            }

        } else {...

        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ListAdapter adapter = new SimpleAdapter(MainParser.this, newslist,
                R.layout.item_cat1, new String[]{ "title_cat1","fulltext_cat1"},
                new int[]{R.id.title_cat1, R.id.fulltext_cat1});
        lv.setAdapter(adapter);
    }
}
编辑: 应用程序启动时崩溃

    E/MainParser: Response from url: [{"id":"6","title_cat1":"Футболист Кокорин пострелял из пистолета на свадьбе в Осетии‍","img_cat1":"http:\/\/legs-legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg","fulltext_cat1":"<p>Нападающий санкт-петербургского Зенита Александр Кокорин пострелял из пистолета во время посещения свадьбы в Осетии. Видео в <b>инстаграме<\/b> спортсмена.<\/p>\r\n<p>Стрельбу в воздух Кокорин назвал дебютом.<\/p>\r\n<p>Ранее сообщалось, что Кокорин выложил в инстагреме фотографию с пистолетом, но позже удалил ее.<\/p>","doptext_cat1":"Любой текст"},{"id":"5","title_cat1":"Футболист Кокорин пострелял из пистолета на свадьбе в Осетии‍","img_cat1":"http:\/\/legs-legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg","fulltext_cat1":"<p>Нападающий санкт-петербургского Зенита Александр Кокорин пострелял из пистолета во время посещения свадьбы в Осетии. Видео опубликовано в <b>инстаграме<\/b> спортсмена.<\/p>\r\n<p>Стрельбу в воздух Кокорин назвал дебютом.<\/p>\r\n<p>Ранее сообщалось, что Кокорин выложил в инстагреме фотографию с пистолетом, но позже удалил ее.<\/p>","doptext_cat1":"любой текст"},{"id":"4","title_cat1":"Футболист Кокорин пострелял из пистолета на свадьбе в Осетии‍","img_cat1":"http:\/\/legs-legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg","fulltext_cat1":"<p>Нападающий санкт-петербургского Зенита Александр Кокорин пострелял из пистолета во время посещения свадьбы в Осетии. Видео опубликовано в <b>инстаграме<\/b> спортсмена.<\/p>\n<p>Стрельбу в воздух Кокорин назвал дебютом.<\/p>\n<p>Ранее сообщалось, что Кокорин выложил в инстагреме фотографию с пистолетом, но позже удалил ее.<\/p>","doptext_cat1":"Любой текст"},{"id":"3","title_cat1":"Футболист Кокорин пострелял из пистолета на свадьбе в Осетии‍","img_cat1":"http:\/\/legs-legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg","fulltext_cat1":"<p>Нападающий санкт-петербургского Зенита Александр Кокорин пострелял из пистолета во время посещения свадьбы в Осетии. Видео опубликовано в <b>инстаграме<\/b> спортсмена.<\/p>\r\n<p>Стрельбу в воздух Кокорин назвал дебютом.<\/p>\r\n<p>Ранее сообщалось, что Кокорин выложил в инстагреме фотографию с пистолетом, но позже удалил ее.<\/p>","doptext_cat1":"Любой текст"},{"id":"2","title_cat1":"Футболист Кокорин пострелял из пистолета на свадьбе в Осетии‍","img_cat1":"http:\/\/legs-legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg","fulltext_cat1":"<p>Нападающий санкт-петербургского Зенита Александр Кокорин пострелял из пистолета во время посещения свадьбы в Осетии. Видео опубликовано в <b>инстаграме
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4d75b20)
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.alexsprod.jsonparserproject, PID: 9985
                  java.lang.NullPointerException
                      at com.alexsprod.jsonparserproject.MainParser$GetData.onPostExecute(MainParser.java:139)
                      at com.alexsprod.jsonparserproject.MainParser$GetData.onPostExecute(MainParser.java:68)
                      at android.os.AsyncTask.finish(AsyncTask.java:632)
                      at android.os.AsyncTask.access$600(AsyncTask.java:177)
                      at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:136)
                      at android.app.ActivityThread.main(ActivityThread.java:5001)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at 

 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                      at dalvik.system.NativeStart.main(Native Method)
E/MainParser:url的响应:[{“id”:“6”,“title_cat1”:“Фббббзбббббббббббзббббб‍","img_cat1:“http:\/\/legs legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg”,“全文_cat1”:"这两个地区的使用情况是作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为збббббббббббббббббббббббббббббббббббббббббббб1073Футболист Кокорин пострелял из пистолета на свадьбе в Осетии‍“,“img\U cat1”:“http:\/\/legs legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg”,“全文\u cat1”:”在这两个地区中使用的是作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为бббззззаааааазззззззааааааааааааааа,ззжжаажааааааааФутболист Кокорин пострелял из пистолета на свадьбе в Осетии‍“,“img\U cat1”:“http:\/\/legs legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg”,“全文\u cat1”:”在这两个地区中,是作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为БКццаззаааааааазааааааааааааа,зааааажааааааажаааааааФутболист Кокорин пострелял из пистолета на свадьбе в Осетии‍“,“img\U cat1”:“http:\/\/legs legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg”,“全文\u cat1”:”在这两个地区中使用的是作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为作为бббззззаааааазззззззааззжжжжжааааааааааааааааааааааФутболист Кокорин пострелял из пистолета на свадьбе в Осетии‍“,“img\U cat1”:“http:\/\/legs legs.ru\/media\/image\/69ac0d3fd5efda52bbd81de7f32c77488ddd9ae4.jpg”,“全文\u cat1”:”аааааааа-аааааааааааааааааааа
D/AndroidRuntime:关闭虚拟机
W/dalvikvm:threadid=1:线程以未捕获异常退出(组=0xa4d75b20)
E/AndroidRuntime:致命异常:主
进程:com.alexsprod.jsonparserproject,PID:9985
java.lang.NullPointerException
位于com.alexsprod.jsonparserproject.MainParser$GetData.onPostExecute(MainParser.java:139)
位于com.alexsprod.jsonparserproject.MainParser$GetData.onPostExecute(MainParser.java:68)
位于android.os.AsyncTask.finish(AsyncTask.java:632)
在android.os.AsyncTask.access$600(AsyncTask.java:177)
位于android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
位于android.os.Handler.dispatchMessage(Handler.java:102)
位于android.os.Looper.loop(Looper.java:136)
位于android.app.ActivityThread.main(ActivityThread.java:5001)
位于java.lang.reflect.Method.Invokenactive(本机方法)
位于java.lang.reflect.Method.invoke(Method.java:515)
在
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
在dalvik.system.NativeStart.main(本机方法)

当您得到
JSONArray
响应时,用下面的代码更改代码

JSONArray array = new JSONArray(jsonStr);

for (int i = 0; i < array.length(); i++) {
  JSONObject c= array.getJSONObject(i);
  String id = c.getString("id");
  String title_cat1 = c.getString("title_cat1");
  String fulltext_cat1 = c.getString("fulltext_cat1");

  // tmp hash map for single contact
  HashMap<String, String> news_item = new HashMap<>();

 // adding each child node to HashMap key => value
  news_item.put("id", id);
  news_item.put("title_cat1", title_cat1);
  news_item.put("fulltext_cat1", fulltext_cat1);
 //contact.put("mobile", mobile);

 // adding contact to contact list
 newslist.add(news_item);
}
JSONArray数组=新的JSONArray(jsonStr);
对于(int i=0;iJSONArray array = new JSONArray(jsonStr);

for (int i = 0; i < array.length(); i++) {
  JSONObject c= array.getJSONObject(i);
  String id = c.getString("id");
  String title_cat1 = c.getString("title_cat1");
  String fulltext_cat1 = c.getString("fulltext_cat1");

  // tmp hash map for single contact
  HashMap<String, String> news_item = new HashMap<>();

 // adding each child node to HashMap key => value
  news_item.put("id", id);
  news_item.put("title_cat1", title_cat1);
  news_item.put("fulltext_cat1", fulltext_cat1);
 //contact.put("mobile", mobile);

 // adding contact to contact list
 newslist.add(news_item);
}
public class CatOneFragment extends Fragment {

public ListView lv;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fr_cat1, container, false);
    lv = (ListView) view.findViewById(R.id.list_cat1);
    new GetData().execute();
    return view;
}


class GetData extends AsyncTask<Void, Void, Void> {

    private ArrayList<HashMap<String, String>> newslist = new ArrayList<>();


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Toast.makeText("Json Data is downloading", Toast.LENGTH_LONG).show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String url = "http://legs-legs.ru/cat1json.php?json=cat1";
        String jsonStr = sh.makeServiceCall(url);
        newslist = new ArrayList<>();
        Log.e(TAG, "Response from url: " + jsonStr);
        if (jsonStr != null) {
            try {

                JSONArray array = new JSONArray(jsonStr);
                for (int i = 0; i < array.length(); i++) {
                    JSONObject c = null;
                    c = array.getJSONObject(i);
                    String id = c.getString("id");
                    String title_cat1 = c.getString("title_cat1");
                    String fulltext_cat1 = c.getString("fulltext_cat1");
                    // tmp hash map for single contact
                    HashMap<String, String> news_item = new HashMap<>();
                    news_item.put("id", id);
                    news_item.put("title_cat1", title_cat1);
                    news_item.put("fulltext_cat1", fulltext_cat1);
                    newslist.add(news_item);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                //CANNOT RESOLVE METHOD
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //CANNOT RESOLVE METHOD
                        Toast.makeText(getActivity(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }
                });

            }

        } else {
            Log.e(TAG, "Couldn't get json from server.");
            //CANNOT RESOLVE METHOD
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //CANNOT RESOLVE METHOD
                    Toast.makeText(getActivity(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG).show();
                }
            });
        }

        return null;
    }

    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        SimpleAdapter adapter = new SimpleAdapter(getActivity(), newslist,
                R.layout.item_cat1, new String[]{"title_cat1", "fulltext_cat1"},
                new int[]{R.id.title_cat1, R.id.fulltext_cat1});
        //CANNOT RESOLVE SYMBOL
        lv.setAdapter(adapter);
    }
}
  <?xml version="1.0" encoding="utf-8"?>
  <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/flContent"
      app:layout_behavior="@string/appbar_scrolling_view_behavior"
      tools:context="com.alexsprod.jsonparserproject.MainParser"
      tools:showIn="@layout/app_bar_main_parser">

      <ListView
          android:id="@+id/list_cat1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/error_connecting"
          app:layout_constraintBottom_toBottomOf="parent"
          app:layout_constraintLeft_toLeftOf="parent"
          app:layout_constraintRight_toRightOf="parent"
          app:layout_constraintTop_toTopOf="parent" />

  </android.support.constraint.ConstraintLayout>
        JSONArray array = new JSONArray(jsonStr);
        for (int i = 0; i < array.length(); i++) {
        JSONObject c= null;
        c = array.getJSONObject(i);
        String id = c.getString("id");
        String title_cat1 = c.getString("title_cat1");
        String fulltext_cat1 = c.getString("fulltext_cat1");
        // tmp hash map for single contact
        HashMap<String, String> news_item = new HashMap<>();
        news_item.put("id", id);
        news_item.put("title_cat1", title_cat1);
        news_item.put("fulltext_cat1", fulltext_cat1);
        newslist.add(news_item);
compile 'com.android.volley:volley:1.1.0'
    public class MainParser extends AppCompatActivity {
        private ListView lv;
        private ArrayList<HashMap<String, String>> newslist;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main_parser);

            newslist = new ArrayList<>();
            lv = (ListView) findViewById(R.id.list_cat1);

            StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://legs-legs.ru/cat1json.php?json=cat1",
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String jsonStr) {

                            try {

                                JSONArray array = new JSONArray(jsonStr);
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject c = null;
                                    c = array.getJSONObject(i);
                                    String id = c.getString("id");
                                    String title_cat1 = c.getString("title_cat1");
                                    String fulltext_cat1 = c.getString("fulltext_cat1");
                                    // tmp hash map for single contact
                                    HashMap<String, String> news_item = new HashMap<>();
                                    news_item.put("id", id);
                                    news_item.put("title_cat1", title_cat1);
                                    news_item.put("fulltext_cat1", fulltext_cat1);
                                    newslist.add(news_item);
                                }
                                SimpleAdapter adapter = new SimpleAdapter(MainParser.this, newslist,
                                        R.layout.item_cat1, new String[]{"title_cat1", "fulltext_cat1"},
                                        new int[]{R.id.title_cat1, R.id.fulltext_cat1});
                                lv.setAdapter(adapter);

                            } catch (final JSONException e) {

                            }


                        }

                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println("error" + error);
                }
            });
            //Creating a Request Queue
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            //Adding request to the queue
            requestQueue.add(stringRequest);


        }


    }