如何使用在Android Studio中的onResponse方法内部定义的变量的值

问题描述 投票:0回答:1

我所要做的就是保存数据库中的一对列表,以供稍后在代码中使用,但是当在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);
    }
}
android json database android-volley jsonresponse
1个回答
1
投票

由于在load()函数中,您正在后台使用JsonArrayRequest调用API,因此System.out.println(thing)中的onCreate()会在从服务器获取响应之前进行调用。这就是thing数组为空的原因。

© www.soinside.com 2019 - 2024. All rights reserved.