JSONObject上的java.lang.NullPointerException

时间:2017-08-13 20:39:12

标签: android fragment

我正在尝试使用JSON从MySQL数据库中检索数据,以便在android studio中的片段列表视图中显示,但由于java.lang.NullPointerException,我的应用程序在运行时停止。您可以帮我修复这个错误请。 我的片段代码是:

 package com.sawaset.rpl;

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

/**
 Created by Sibo on 7/25/2017.
 **/

public class timetable extends Fragment {
   private String jsonResult=null;
    public String address = "http://127.0.0.1/projects/soccer/query.php";
    ListView listview;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

             View rootView = inflater.inflate(R.layout.table_tab, container, false);

      listview = (ListView) rootView.findViewById(android.R.id.list);
        /*ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,menus);
        lv.setAdapter(adapter);*/
        accessWebService();
        return rootView;
    }

    //
    private class jsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httPost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httPost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        //
        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            } catch (IOException e) {
                Toast.makeText(getActivity(), "Error:" + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;

        }

        @Override
        protected void onPostExecute(String result) {

            drawer();
        }

    }
//

    public void accessWebService() {
        jsonReadTask task = new jsonReadTask();
        task.execute(new String[]{address});
    }

    public void drawer() {
        try {
            JSONObject jsonResponse = new JSONObject(jsonResult.substring(jsonResult.indexOf("{"), jsonResult.lastIndexOf("}") + 1));
           JSONArray jsonMainNode = jsonResponse.getJSONArray("teams");

            final ArrayList<HashMap<String, String>> MyarrList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;
            if (jsonMainNode!= null) {
                for (int i = 0; i < jsonMainNode.length(); i++) {
                    JSONObject c = jsonMainNode.getJSONObject(i);
                    map = new HashMap<String, String>();

                    map.put("t_id", c.getString("t_id"));
                    map.put("t_id", c.getString("t_id"));
                    map.put("t_id", c.getString("t_id"));

                    MyarrList.add(map);

                    SimpleAdapter sAdp = new SimpleAdapter(getActivity(), MyarrList, R.layout.columns, new String[]{"t_id", "t_id", "t_id"}, new int[]{R.id.col1, R.id.col2, R.id.col3});
                    listview.setAdapter(sAdp);
                }
            }
        } catch (JSONException e) {
            Toast.makeText(getActivity(), "Error:" + e.toString(), Toast.LENGTH_LONG).show();
        }
    }
}

logcat如下所示

 HostConnection::get() New Host Connection established 0x9bbdd240, tid 17548
08-13 22:07:20.395 17531-17531/com.sawaset.rpl E/AndroidRuntime: FATAL EXCEPTION: main
                                                                 Process: com.sawaset.rpl, PID: 17531
                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(java.lang.String)' on a null object reference
                                                                     at com.sawaset.rpl.timetable.drawer(timetable.java:105)
                                                                     at com.sawaset.rpl.timetable$jsonReadTask.onPostExecute(timetable.java:92)
                                                                     at com.sawaset.rpl.timetable$jsonReadTask.onPostExecute(timetable.java:55)
                                                                     at android.os.AsyncTask.finish(AsyncTask.java:667)
                                                                     at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                     at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
08-13 22:07:21.056 1280-1280/? E/EGL_emulation: tid 1280: eglCreateSyncKHR(1669): error 0x3004 (EGL_BAD_ATTRIBUTE)
08-13 22:07:21.847 2415-17536/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 2753, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
08-13 22:07:21.853 2415-17536/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
08-13 22:07:21.853 2415-17536/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
08-13 22:07:21.856 2415-17536/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
08-13 22:07:27.002 2415-17536/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 2761, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
08-13 22:07:27.004 2415-17536/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.
08-13 22:07:27.006 2415-17536/com.google.android.googlequicksearchbox:search E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
08-13 22:07:27.007 2415-17536/com.google.android.googlequicksearchbox:search E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
08-13 22:07:32.099 2415-17536/com.google.android.googlequicksearchbox:search E/AudioRecord: Could not get audio input for session 2769, record source 1999, sample rate 16000, format 0x1, channel mask 0x10, flags 0
08-13 22:07:32.100 2415-17536/com.google.android.googlequicksearchbox:search E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -22.

任何帮助都非常感谢

1 个答案:

答案 0 :(得分:0)

java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.indexOf(java.lang.String)' on a null object reference

at com.sawaset.rpl.timetable.drawer(timetable.java:105)

这意味着 timetable.drawer 中的第105行存在空对象引用。我相信这是以下代码行:

final ArrayList<HashMap<String, String>> MyarrList = new ArrayList<HashMap<String, String>>();

唯一一次为MyarrList分配任何值的时间都在if (jsonMainNode!= null)的第107行的timetable.drawer检查中。因此,如果jsonMainNode等于null,那么您的MyarrList也将为空。

正如Selvin在下面提到的,解决导致null jsonResult的路径时出错将导致null jsonResponse,这将导致null jsonMainNode并抛出NullPointerException。