2

Here is the code I'm using inside my AsyncTask

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);    
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");

HttpResponse response = httpClient.execute(request);

HttpEntity responseEntity = response.getEntity();

char[] buffer = new char[(int)responseEntity.getContentLength()];
    InputStream stream = responseEntity.getContent();
    InputStreamReader reader = new InputStreamReader(stream);
    reader.read(buffer);
    stream.close();

    result = new String(buffer);
    return result;

This returns a string result and in my onPostExecute method I try to parse that input string:

JSONObject vehicle = new JSONObject(new String(result));
makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));

As soon as it reaches makeEdit.setText it throws an error - no value for make. I'm still very new to android, so don't send death threats if there was some obvious error. The input text is the following JSON string:

{"GetJSONObjectResult":{"make":"Ford","model":"Focus","plate":"XXO123GP","year":2006}}
Cloud9999Strife
  • 3,102
  • 3
  • 30
  • 43

2 Answers2

9

No value for x error message is pretty common when dealing with JSON. This usually resulted by overlooked code.

usually, when dong JSON, I try to see the human readable structure first. For that, I usually use JSONViewer.

In your case, the structure is something like this:

enter image description here

You see that make is within another object called GetJSONObjectResult. Therefore, to get it, you must first get the container object first:

JSONObject vehicle = ((JSONObject)new JSONObject(result)).getJSONObject("GetJSONObjectResult");
//a more easy to read
JSONObject container = new JSONObject(result);
JSONObject vehicle = container.getJSONObject("GetJSONObjectResult");

and finally use the object to get make:

makeEdit.setText(vehicle.getString("make"));
plateEdit.setText(vehicle.getString("plate"));
modelEdit.setText(vehicle.getString("model"));
yearEdit.setText(vehicle.getString("year"));
ariefbayu
  • 21,849
  • 12
  • 71
  • 92
4

Your JSON Object contains itself a JSONObject. To acces to your data, you have to do like this:

vehicle.getJSONObject("GetJSONObjectResult").getString("make");
Jeje Doudou
  • 1,707
  • 1
  • 16
  • 24