Title: Getting NullPointer Exception while parsing JSON
Tags: android;json;nullpointerexception
Question: I am trying to parse json from webservices but i get nullpointer exception. But if i hit url in browser then i get results but in code it's returning null.   

Here is my url:- http://www.expensekeeper.in/webservice/FetchBillCall.php?userid=7  

Here is my code:-  

```@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    new LongOperation().execute("");

}

private class LongOperation extends AsyncTask<String, Void, String&gt; {
    @Override
    protected String doInBackground(String... params) {
        String url = "http://www.expensekeeper.in/webservice/FetchBillCall.php?userid=7";
         JSONParser jsonParser = new JSONParser();
         JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
         try {
             //JSONArray jsonArray = jsonObject.getJSONArray("");
            dueDate = jsonObject.getString("duedate");
            description = jsonObject.getString("description");
            status = jsonObject.getString("status");
            remarks = jsonObject.getString("remarks");
        } catch (JSONException e) {
        e.printStackTrace();
        }
          return "Executed";
    }  
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(MainActivity.this, dueDate+description+status+remarks, Toast.LENGTH_LONG).show();
   }

   }
```

Here is my jsonParser class:-  

```public JSONObject getJSONFromUrl(String str) {

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        URL url = new URL(str);
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
        json = jsonResults.toString();
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
     try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }
     return jObj;

}   
```

And here is my stacktrace:-   

```04-10 17:15:16.425: E/AndroidRuntime(1388): Caused by: java.lang.NullPointerException
04-10 17:15:16.425: E/AndroidRuntime(1388):     at com.example.jsonsample.MainActivity$LongOperation.doInBackground(MainActivity.java:40)
04-10 17:15:16.425: E/AndroidRuntime(1388):     at com.example.jsonsample.MainActivity$LongOperation.doInBackground(MainActivity.java:1)   
```

I don't understand what going wrong in my code. Why i am getting null value from server.
Please give me any reference.
Thanks in advance

Comment: Where does `(MainActivity.java:40)` point to?

Comment: on `dueDate = jsonObject.getString("duedate");`.

Here is the accepted answer: Edit:

Change type returned by  ```getJSONFromUrl(String str)``` from ```JSONObject``` to ```JSONArray```.

And then create JSONArray directly like this

```JSONArray array=new JSONArray(json);```   // json is your json string

return array in the ```getJSONFromUrl(String str)``` method



Your Service returning JSONArray

Based on the above response, your service returning JSONArray , not JSONObject, so it will also throw JSONException, when you try to convert JSONArray to JSONObject.

```  JSONObject jsonObject = jsonParser.getJSONFromUrl(url);
```

So this will return you null,

as your jsonObject is ```null``` and you are trying to access it here

```dueDate = jsonObject.getString("duedate");
```

You will get ```NullPointerException```

Comment for this answer: you can directly create JSONArray with the string, do like this  `JSONArray array = new JSONObject(jsonstring);` and return JSONArray in the JSON Parser
Comment for this answer: can you provide me how to read array without having any name... because my array dont have any name.... have you hit this url...


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:04/10/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<android><json><nullpointerexception>', 'Title': 'Getting NullPointer Exception while parsing JSON', 'ViewCount': 2938, 'id': 15932363, 'user_AboutMe': '<p>Android Developer in <a href="http://www.programr.com/" rel="nofollow">Programr</a> , Pune. My responsibility it to develop Android Application. I also work on HTML5, JavaScript. I love Reading. I like to travel and visit historical places. Here is my <a href="http://sanarmal.blogspot.in" rel="nofollow">Android Blog</a>.   </p>\n\n<p>Here is my two Android App.<br>\n<a href="https://play.google.com/store/apps/details?id=com.appstage.areapinfinder&amp;hl=en" rel="nofollow">Find Anything</a> and <a href="https://play.google.com/store/apps/details?id=com.appstage.babyimmunisation&amp;hl=en" rel="nofollow">We care baby</a></p>\n', 'user_AccountId': 1159601.0, 'user_DisplayName': 'Sandip Armal Patil', 'user_Reputation': 6333.0, 'user_Views': 2468.0, 'user_id': 1139398.0}}