JSONArray response with Volley for Android

前端 未结 2 1695
孤城傲影
孤城傲影 2021-01-12 07:09

I am posting some data into the database using Volley and I get the following jsonarray response.

[
  {
  \"nickname\":\"panikos\",
  \"username\":\"panikos@         


        
相关标签:
2条回答
  • 2021-01-12 07:58

    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 I am assigned to do is going to have more complicate webservices.omg!!!

    0 讨论(0)
  • 2021-01-12 08:07

    I the problem might be - you are already getting response as a JSONArray.

    So, you can Call

    JSONObject jresponse = response.getJSONObject(0);

    and if you have more than 1 object in response, then

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

    Remove this :

                   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, however i think you might be missing a call to add jsonObjReq1 in the request queue. I would suggest to use Singleton Pattern.

    0 讨论(0)
提交回复
热议问题