ArrayList being empty after adding elements

后端 未结 2 787
失恋的感觉
失恋的感觉 2020-12-01 23:31

I have this android code which bring a JSON from a server and fill an ArrayList from that JSON I checked the size of the ArrayList \"meals\" inside the onresponse void it gi

2条回答
  •  不知归路
    2020-12-01 23:50

    The problem here is about understanding how asynchronous tasks work. When you are adding a volley request to the queque, it will run in background thread (off the main thread) and control will pass to the next line.

    So, after this:

    Volley.newRequestQueue(getActivity()).add(mealsrequest);
    

    control passes to this:

    ArrayList strs=new ArrayList();
    String mealsnames[]=new String[meals.size()];
    

    Now since meals is updated on the background thread, you are not able to get the data by the time control reaches String mealsnames[]=new String[meals.size()];

    So you will get zero size (meals.size()) here.

    Try to move this portion of the code into onResponse.

    Try like this:

    public void updateData(){
       ArrayList strs=new ArrayList();
       String mealsnames[]=new String[meals.size()];
       for(int i=0;i

    and call this method from onResponse:

    @Override
    public void onResponse(String response) {
        try{
            JSONObject object= new JSONObject(response);
            JSONArray mealsArray = object.getJSONArray("result");
            for(int i=0;i
                                                            
提交回复
热议问题