JSONArray answer with Volley for Android

I send some data to the database using Volley and I get the following jsonarray response.

[ { "nickname":"panikos", "username":" panikos@gmail.com ", "user_type":"LEADER", "latest_steps":"0" } ] 

This is a sample of my code, which, unfortunately, does not output or debug the object variable "nickname": (.

 final JsonArrayRequest jsonObjReq1 = new JsonArrayRequest(AppConfig.URL_GET_TEAM, jsonObject, new com.android.volley.Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("TAG", response.toString()); try { JSONArray jsonArray = new JSONArray(response); for(int i=0;i<jsonArray.length();i++){ JSONObject jresponse = jsonArray.getJSONObject(i); String nickname = jresponse.getString("nickname"); Log.d("nickname",nickname); } } catch (JSONException e) { e.printStackTrace(); } //pDialog.dismiss(); } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d("TAG", "Error: " + error.getMessage()); //pDialog.dismiss(); } }) { @Override public String getBodyContentType() { return "application/json; charset=utf-8"; } }; 

Any ideas? Am I missing something?

Thanks.

+7
json android android-volley
source share
2 answers

I have a problem: you are already receiving response as a JSONArray .

So you can call

JSONObject jresponse = response.getJSONObject(0);

and if the answer has more than one object, then

 for(int i = 0; i < response.length(); i++){ JSONObject jresponse = response.getJSONObject(i); String nickname = jresponse.getString("nickname"); Log.d("nickname", nickname); } 

Take this off:

  try { JSONArray jsonArray = new JSONArray(response); for(int i=0;i<jsonArray.length();i++){ JSONObject jresponse = jsonArray.getJSONObject(i); String nickname = jresponse.getString("nickname"); Log.d("nickname",nickname); } } catch (JSONException e) { e.printStackTrace(); } 

and add:

 try { JSONObject jresponse = response.getJSONObject(0); String nickname = jresponse.getString("nickname"); Log.d("nickname",nickname); }catch (JSONException e) { e.printStackTrace(); } 

The code looks good, but I think you might miss the call to add jsonObjReq1 to the request queue. I suggest using a Singleton Pattern .

+8
source share

Fixed!!!

  @Override public void onResponse(JSONArray response) { Log.d("TAG", response.toString()); try { Log.d("JsonArray",response.toString()); for(int i=0;i<response.length();i++){ JSONObject jresponse = response.getJSONObject(i); String nickname = jresponse.getString("nickname"); Log.d("nickname",nickname); } } catch (JSONException e) { e.printStackTrace(); } //pDialog.dismiss(); } 

There was no need to create a new JSONArray. It was created inside the onResponse () method. The next project to which I am assigned will complicate webservices.omg more !!!

+1
source share

All Articles