【问题标题】:Volley and Fragments - how to wait for a request to endVolley 和 Fragments - 如何等待请求结束
【发布时间】:2014-12-05 17:10:28
【问题描述】:

我正在使用 Volley 请求 JSONArray。同时,我在我的 Activity 中创建 Fragments,其中之一是 ListFragment。我必须使用从该请求中获得的 Array 填充列表。但是 Fragments 中的 onCreateView() 在我得到结果中的数组之前被调用,导致 ListView 中显示一个空数组。

我可以做些什么来使这个同步或稍等片刻或在填充数组时让列表重绘自己?

我已经尝试过 Volley Future Request,但我不知道如何将它们与我的请求中的自定义侦听器一起使用。

【问题讨论】:

    标签: android android-fragments android-volley


    【解决方案1】:

    您的 ListView 应该有某种数据适配器,可能是 ArrayAdapter,与之相关联(您需要创建它,它不是自动的)。

    如果您使用ArrayAdapter,则在您的 Volley 请求的侦听器中,add()/addAll() 将您的结果输入适配器。适配器会自动导致 ListView 刷新。

    如果您创建了自己的适配器类型不是从 ArrayAdapter 派生的,则必须手动处理更改通知。这就是notifyDataSetChanged() 所做的——只需在适配器中进行更改后调用它,它就会刷新视图。

    【讨论】:

    • 我确实有一个扩展 BaseAdapter 的自定义适配器,所以它应该是 notyfing?还是什么都没有。
    • 不,我认为 BaseAdapter 不会自动通知。您需要手动调用notifyDataSetChanged()
    【解决方案2】:

    我相信 Volley 可以根据您的请求处理回调侦听器。

    final TextView mTextView = (TextView) findViewById(R.id.text);
    ...
    
    // Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="http://www.google.com";
    
    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener() {
     @Override
     public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
     }
    }, new Response.ErrorListener() {
     @Override
     public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
     }
    });
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
    

    this link 复制上述代码。也许你可以更新列表视图 onResponse() 回调。

    【讨论】:

    • 我现在正在尝试这个。每次创建视图时都调用一个新的适配器来让它工作,但是对于一个大列表来说它是完全没有效率的。我会尝试将其转换为响应,以便仅在请求更新时才能更改。
    猜你喜欢
    • 2016-10-04
    • 2023-04-05
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多