【问题标题】:How to use the value of a variable that was defined inside the onResponse method in Android Studio如何使用在 Android Studio 的 onResponse 方法中定义的变量的值
【发布时间】:2020-02-24 02:53:46
【问题描述】:

我所需要的只是保存数据库中的一对列表,以便稍后在代码中使用它们,但是当在 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);
    }
}

【问题讨论】:

  • ShareDPreferences 是答案。

标签: android json database android-volley jsonresponse


【解决方案1】:

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

【讨论】:

  • 我怎么能让程序等待服务器的响应,有评论说ShareDPreferences就是答案,我应该试试吗?
  • 简单,你可以在onResponse()下执行你的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多