getJSONfromURL - Null Pointer Exception

2019-08-12 17:15发布

问题:

I made an activity "Messages" which is supposed to get JSON data from a given URL. I tried making a loop to print the json data, but the problem was somewhere else. I am getting NullPointerException on the JSONArray, "json".

Messages class:

public class Messages extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView tv = (TextView) findViewById(R.id.tv_messages);
    JSONArray json = JSONfunctions.getJSONfromURL("http://docs.blackberry.com/sampledata.json");

    tv.setText(json.length());
}

JSONfunctions class:

public class JSONfunctions {

    public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag get data string ",
                    "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag create object ",
                    "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

Error:

08:11:43.683: Error in http connection android.os.NetworkOnMainThreadException 08:11:43.693: Error converting result java.lang.NullPointerException: lock == null 08:11:43.703: Error parsing data org.json.JSONException: End of input at character 0 of 08:11:43.723: Shutting down VM 08:11:43.733: threadid=1: thread exiting with uncaught exception (group=0x40a70930) 08:11:43.923: ATAL EXCEPTION: main 08:11:43.923: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sound/com.example.sound.Messages}: java.lang.NullPointerException 08:11:43.923: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 08:11:43.923: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 08:11:43.923: at android.app.ActivityThread.access$600(ActivityThread.java:141) 08:11:43.923: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 08:11:43.923: at android.os.Handler.dispatchMessage(Handler.java:99) 08:11:43.923: at android.os.Looper.loop(Looper.java:137) 08:11:43.923: at android.app.ActivityThread.main(ActivityThread.java:5039) 08:11:43.923: at java.lang.reflect.Method.invokeNative(Native Method) 08:11:43.923: at java.lang.reflect.Method.invoke(Method.java:511) 08:11:43.923: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 08:11:43.923: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 08:11:43.923: at dalvik.system.NativeStart.main(Native Method) 08:11:43.923: Caused by: java.lang.NullPointerException 08:11:43.923: at com.example.sound.Messages.onCreate(Messages.java:18) 08:11:43.923: at android.app.Activity.performCreate(Activity.java:5104) 08:11:43.923: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 08:11:43.923: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

The line 18 is:

tv.setText(json.length());

Prior to the above errors, I also get many:

Unexpected value from nativeGetEnabledTags: 0

The URL I'm using (for testing purposes, http://docs.blackberry.com/sampledata.json) is up and working. I'm new to Android Developing and JSON. Thanks in advance.

回答1:

This is because either you are performing network operation on main thread which in not allowed android version >= 3.0.

To solve this either use

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy); 

OR

Use AsyncTask 

Read from http://developer.android.com/reference/android/os/AsyncTask.html



回答2:

Thanks to @TGMCians, ASyncTask did the job. Here's what my activity looks like now:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class Messages extends Activity {
    String THEURL = "http://docs.blackberry.com/sampledata.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_messages);
        new RetrieveMessages().execute(THEURL);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        finish();
    }
    private class RetrieveMessages extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            HttpClient client = new DefaultHttpClient();
            String json = "";
            try {
                String line = "";
                HttpGet request = new HttpGet(urls[0]);
                HttpResponse response = client.execute(request);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                while ((line = rd.readLine()) != null) {
                    json += line + System.getProperty("line.separator");
                }
            } catch (IllegalArgumentException e1) {
                e1.printStackTrace();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            return json;
        }

        protected void onProgressUpdate(Void... progress) {

        }

        protected void onPostExecute(String result) {
            TextView tv = (TextView) findViewById(R.id.tv_messages);
            tv.setText(result);
        }
    }
}