Prakhar
Prakhar

Reputation: 710

NullPointer on JSON Array Android

I am getting this response from server:

status: "ok",
response: {
suggestions: [
{
suggestion: "Cetri (10 mg)"
},
{
suggestion: "Cetri-Plus (300 & 10)"
 },
{
suggestion: "Cetriax (1000 mg)"
},
{
suggestion: "Cetricon (10 mg)"
},
{
suggestion: "Cetrics (500 & 5 & 5)"
}
]
}

And I am doing this to get the values:

String result = Utils.convertInputStreamToString(inputStream);

            //Printing server response
            System.out.println("server response is :" + result + "\n" + inputStream);


            try {
                JSONObject jsonResponse = new JSONObject(result);
                js=jsonResponse.getJSONArray("suggestions");


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }

But the app crashes with a null pointer exception that

05-21 12:42:04.217: W/System.err(25961): org.json.JSONException: No value for suggestions

What am I missing? Please help... Thanx

Upvotes: 0

Views: 152

Answers (3)

ThanhND25
ThanhND25

Reputation: 86

Because your List's name and Object in List's name are the same. I suggest you using my function

 /** @param jObject The JSONObject to convert.
 *   @return A list of two item lists: [String key, Object value].
 *   @throws JSONException if an element in jObject cannot be
 *   converted properly.
 */
@SuppressWarnings("unchecked")
 public static List<Object> getListFromJsonObject(JSONObject jObject) throws JSONException {
      List<Object> returnList = new ArrayList<Object>();
      Iterator<String> keys = jObject.keys();
      List<String> keysList = new ArrayList<String>();
  while (keys.hasNext()) {
    keysList.add(keys.next());
  }
  Collections.sort(keysList);

  for (String key : keysList) {
    List<Object> nestedList = new ArrayList<Object>();
    nestedList.add(key);
    nestedList.add(convertJsonItem(jObject.get(key)));
    returnList.add(nestedList);
  }
  return returnList;
}

Upvotes: 0

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5634

You are getting JSONException as your JSONArray suggestions is inside response JSONObject. So you require to do

JSONObject jsonResponse = new JSONObject(result);
jsonResponse = jsonResponse.getJSONObject ("response");

//and now you can use your code.
js=jsonResponse.getJSONArray("suggestions");

Upvotes: 1

Kelevandos
Kelevandos

Reputation: 7082

Try this:

JSONObject mainNode = new JSONObject(result);
JSONObject jsonResponse = mainNode.getJSONObject("response");
js=jsonResponse.getJSONArray("suggestions");

Upvotes: 3

Related Questions