0

Could someone please explain or correct as to why I am getting a null pointer exception in my Async Class? I am trying to get data from a URL but get a null pointer exception for the 162, which contains the following code

int lengthJsonArr = jsonMainNode.length();

I am not sure as to why that is but if someone could help that would be great. or if someone can show me a better alternative to fetch json data from url that would also be a great help.

public class userTask extends AsyncTask<String, Void, Void>{
    HttpURLConnection connection = null;
    private String Content;
    @Override
    protected Void doInBackground(String... urls) {

        BufferedReader reader = null;
        try {
            URL url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            } Content = buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void s) {
        super.onPostExecute(s);

        String OutputData = "";
        JSONObject jsonResponse;

        try {
            jsonResponse = new JSONObject(Content);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

            int lengthJsonArr = jsonMainNode.length(); //This is causing the exception

            for (int i =0; i < lengthJsonArr; i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("name").toString();
                Double longitude = jsonChildNode.optDouble("lon");
                Double latitude = jsonChildNode.optDouble("lat");

                OutputData += " Name : "+ name +" "
                        + "Longitude : "+ longitude +" "
                        + "Latitude  : "+ latitude +" "
                        +"-------------------------------------------------- ";

                //Show Parsed Output on screen (activity)
                Toast toast = Toast.makeText(getApplicationContext(), OutputData, Toast.LENGTH_LONG);
                toast.show();


            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
4
  • Don't make Content an instance variable in the AsyncTask. You should return it from doInBackground and operate on it in onPostExecute Commented Mar 26, 2016 at 15:04
  • "a better alternative to fetch json data from url" - the Volley or OkHttp libraries are great alternatives, but that doesn't solve the fact you are getting a null value from your JSON object for the Android array. Commented Mar 26, 2016 at 15:07
  • Your doInBackground() should return the String content, and the onPostExecut should receive that string as input (parameter). So you also have to modify as AsyncTask<String, Void, String> Commented Mar 26, 2016 at 15:10
  • yah you can use Volley as suggested by @cricket_007 Its very easy to make request with it. Commented Mar 26, 2016 at 15:12

2 Answers 2

1

This is not a good way to fetch JSON data in android. You should use Volley or Retrofit library. These libraries will work accuratly and efficiently than normal code.

There are alot of things to take care of while fetching data. All will be done by library. And you just need to write few lines of code.

You can follow many good tutorials on google.

Sign up to request clarification or add additional context in comments.

5 Comments

I have been trying to look into those libraries but cannot find a decent tutorial if you could provide me with a link that explains it that would be great.
you can find more info in this link volley you can find a great video about the volley in this link. good luck
you can follow this link : youtube.com/watch?v=FzwBYPzCIHk in this link RequestQueue is created in normal class. Recommended to create RequestQueue Object using Singleton class. Bcz it is expensive.
@vabhivab what is the latest version of Volley? when I googled it, it said that it is deprecated
you need to add this dependancy compile 'com.android.volley:volley:1.0.0' Check this link : github.com/mcxiaoke/android-volley
0

As this works...

jsonResponse = new JSONObject(Content);

...you at least succesfully receive a HTTP response which contains a valid JSON object.

The next line...

JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

...tries to extract a JSON array, but apparently fails and as a result your jsonMainNode variable is null. That is how optJSONArray() works. It just returns null if it does not find what was asked for. (Instead of throwing a JSONException for example.)

Then the next line...

int lengthJsonArr = jsonMainNode.length();

...of course fails because you can't get the length of a null JSON array.

So it looks like the JSON you receive does not include an array called "Android". You could/should place a breakpoint on...

JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");

...and check what's in the JSON object. Or just print out the response. (And properly name it "content" with lowercase so people won't nag about the Java coding convention...)

As for avoiding the NullPointerException you could use code like:

if (jsonResponse.has("Android")) {
    JSONArray jsonMainNode = jsonResponse.optJSONArray("Android");
    int lengthJsonArr = jsonMainNode.length();
    // Etc.
    // ...
}
else {
    // TODO: Recover from the situation.
    // ...

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.