首页 > 解决方案 > 如何使用在 Android Studio 的 onResponse 方法中定义的变量的值

问题描述

我所需要的只是保存数据库中的一对列表,以便稍后在代码中使用它们,但是当在 onResponse 方法之外调用时,列表总是显示为空。我是 Android Studio 和数据库的新手。我使用了 Volley 库,这是代码部分的“摘录”,它给我一些打印问题,其中数组是否为空:

    public class Fragmento extends Fragment {

    ArrayList<String> codes = new ArrayList<String>();
    ArrayList<String> names = new ArrayList<String>();
    ArrayList<ArrayList<String>> thing= new ArrayList<ArrayList<String>>();;

    RequestQueue requestQueue;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        load();
        System.out.println(thing); //ARRAY IS EMPTY

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragmento, container, false);
    }

    private void load(){
        JsonArrayRequest jsonArrayRequest= new JsonArrayRequest("the url here",new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        JSONObject jsonObject = null;
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                jsonObject = response.getJSONObject(i);
                                codes.add(jsonObject.getString("codigo"));
                                names.add(jsonObject.getString("nombre"));


                            } catch (JSONException e) {
                                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }
                        thing.add(codes);
                        thing.add(names);

                        System.out.println(thing);//ARRAY IS FULL
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getContext(),error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        System.out.println(thing);//ARRAY IS EMPTY

        requestQueue=Volley.newRequestQueue(getActivity());
        requestQueue.add(jsonArrayRequest);
    }
}

标签: androidjsondatabaseandroid-volleyjsonresponse

解决方案


因为在load()函数中你是JsonArrayRequest在后台调用 API,所以System.out.println(thing)onCreate()从服务器获得响应之前调用。这就是thing数组为空的原因。


推荐阅读