-2

I want to add each user response to my list listItem, inserting the response's specific key and value pair. However, in this code, the first loop of getCat() executes 4 times ... then all responses get added to the last key those are 4.

public void getCat(){

    String url = "http://******/*****/*****.json";
    HashMap<String, List<CatType> hmap=new HashMap<String, ArrayList<CatType>>();
    private List<ListItem> listItems;
    for(int i=1;i<5;i++)
       {

       JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
             url, null, new Response.Listener<JSONObject>() {

       @Override
       public void onResponse(JSONObject response) {
           Log.d(TAG, "Response: " + response.toString());
           parseJsonFeed(response);
           listItems = new ArrayList<ListItem>();
           listItem.addAll(O_listItems);
           hmap.put("["+i+"]",listItem);
       }
    }, new Response.ErrorListener() {

       @Override
       public void onErrorResponse(VolleyError error) {
           Log.d(TAG, "Error: " + error.getMessage());
       }
    });

    // Adding request to volley request queue
    AppController.getInstance().addToRequestQueue(jsonReq);
    }
}

private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("food");
        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);
            OrderListItem item=new OrderListItem();
            item.setId(feedObj.getInt("id"));
            item.setImage(feedObj.getString("image"));
            item.setItem_name(feedObj.getString("name"));
            O_listItems.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
Prune
  • 76,765
  • 14
  • 60
  • 81

1 Answers1

0

This is happening because each time you make a request a new thread is created, so before the response comes back from the first hit, a new hit is made and this goes on. For such kind of situation it is better to use AsyncTask or make synchronous hits. See this answer for making synchronous hits.

Community
  • 1
  • 1
varunkr
  • 5,364
  • 11
  • 50
  • 99
  • I implementation as given link. but i am not getting where i have to receive the response from server means, where i have to pass the Json response to parseJson(JSONObject response). – Anupam Tripathi Oct 04 '15 at 10:08
  • JsonObjectRequest request = new JsonObjectRequest(Method.POST, URL_FETCH1+categoryTemp.getId(),null, future, future) ; It 's not working – Anupam Tripathi Oct 04 '15 at 13:11
  • Hi Varnkr as you told I tried AsyncTask also but it not working. please help me. – Anupam Tripathi Oct 05 '15 at 04:15