添加元素后,ArrayList为空 [英] ArrayList being empty after adding elements

查看:105
本文介绍了添加元素后,ArrayList为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Android代码从服务器带来一个JSON并从那个JSON
填充一个ArrayList我检查了响应空间里的ArrayListmeal的大小它给了我1但是当我检查它之后StringRequest对象我得到0项。
餐是在全球范围内定义的,并在oncreateview函数内初始化
代码:

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 gives me 1 but when i check it after the StringRequest object i get 0 items . meals is defined in global scope and initialized inside the oncreateview function The Code:

               public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.i("debug","on create view");
View view =inflater.inflate(R.layout.fragment_meal_list,container,false);
ListView List ;
meals=new ArrayList<meal>();
String url="http://syriankitchen.tk/get_recent.php";
StringRequest mealsrequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

    @Override
    public void onResponse(String response) {
        try{
            JSONObject object= new JSONObject(response);
            JSONArray mealsArray = object.getJSONArray("result");
            for(int i=0;i<mealsArray.length();i++){
                JSONObject cur = mealsArray.getJSONObject(i);
                int id= cur.getInt("id");
                String name= cur.getString("name");
                String description = cur.getString("description");
                int price = cur.getInt("price");
                meals.add(new meal(id,name,price,description));
            }
            Log.i("debug","meals size = "+meals.size());
        }
        catch(JSONException e){
            e.printStackTrace();
        }
    }
},new Response.ErrorListener(){
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(getActivity(),error.getMessage(),Toast.LENGTH_SHORT).show();
    }
});
Volley.newRequestQueue(getActivity()).add(mealsrequest);
ArrayList<String> strs=new ArrayList<String>();
String mealsnames[]=new String[meals.size()];
for(int i=0;i<meals.size();i++)strs.add(meals.get(i).getName());
strs.toArray(mealsnames);
Log.i("debug","meals ou size "+meals.size());
CustomList  adapter = new CustomList(getActivity(),mealsnames,meals);
List = (ListView)view.findViewById(R.id.list);
List.setAdapter(adapter);


推荐答案

这里的问题是如何理解异步任务有效。当您向queque添加 volley 请求时,它将在后台线程(离开主线程)中运行,控件将传递给下一个行。

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.

所以,在此之后:

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

控制转到此:

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

现在,因为饭菜在后台更新线程,你无法在控制时间到达时获取数据 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()];

所以这里你会得到尺寸( meals.size())。

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

尝试将此部分代码移至 onResponse

Try to move this portion of the code into onResponse.

试试这样:

public void updateData(){
   ArrayList<String> strs=new ArrayList<String>();
   String mealsnames[]=new String[meals.size()];
   for(int i=0;i<meals.size();i++)strs.add(meals.get(i).getName());
   strs.toArray(mealsnames);
   Log.i("debug","meals ou size "+meals.size());
   CustomList  adapter = new CustomList(getActivity(),mealsnames,meals);
   List = (ListView)view.findViewById(R.id.list);
   List.setAdapter(adapter);
}

并从 onResponse

@Override
public void onResponse(String response) {
    try{
        JSONObject object= new JSONObject(response);
        JSONArray mealsArray = object.getJSONArray("result");
        for(int i=0;i<mealsArray.length();i++){
            JSONObject cur = mealsArray.getJSONObject(i);
            int id= cur.getInt("id");
            String name= cur.getString("name");
            String description = cur.getString("description");
            int price = cur.getInt("price");
            meals.add(new meal(id,name,price,description));
        }
        Log.i("debug","meals size = "+meals.size());
        updateData();
    }
    catch(JSONException e){
        e.printStackTrace();
    }
}

这篇关于添加元素后,ArrayList为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆