Reputation: 13199
I'm using HttpGet
method in my REST API
on Android and I have a problem. I get the response but I can't create the object that it's being retrieved. Here I put my AsyncTask
:
class FindCar extends AsyncTask<Integer, Integer, Void> {
protected void onPreExecute(){
}
protected Void doInBackground(Integer... idCar) {
String name = "";
String url = "http://IP of my computer/project/cars/" + idCar[0].intValue();
HttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
method.setHeader("content-type", "application/json");
try {
HttpResponse resp = httpClient.execute(method);
String respStr = EntityUtils.toString(resp.getEntity());
Log.d("prove", respStr); //Here I get {"name":"Car1"}
JSONObject obj = new JSONObject(respStr);
name = obj.getString("name");
Log.d("prove", name); //Nothing appears
} catch (Exception ex) {
}
return null;
}
protected void onProgressUpdate(){
}
protected void onPostExecute(){
}
}
Why, if my response it's being retrieved, the object isn't created? Am I doing something wrong?
EDIT: I make a lot of proves and in my real code I have respStr
but I copy the prove that I make before. Sorry.
Thanks in advance!
Upvotes: 0
Views: 609
Reputation: 13199
SOLUTION:
Finally I got the solution. What I did?
Remove this sentence:
name = obj.getString("name");
and rewrite it again (put exactly the same as before).
And works! Just incredible...
Please if someone knows what happens here let me know. I'm really intrigued about this.
Upvotes: 1
Reputation: 5261
What is i??
Instead of doing this:
JSONObject obj = respJSON.getJSONObject(i);
Do this:
JSONObject obj = new JSONObject(respStr);
Upvotes: 0
Reputation: 75645
You got response in respStr
but you do not seem to use it anywhere, you got respJSON
which is who-knows-what and you use it for unknown reason and not to mention you use i
which comes out of nowhere. You should create your response JSON just like that:
String respStr = EntityUtils.toString(resp.getEntity());
JSONObject obj = new JSONObject(respStr);
Upvotes: 0