【问题标题】:Android call notifyDataSetChanged from AsyncTaskAndroid 从 AsyncTask 调用 notifyDataSetChanged
【发布时间】:2013-05-02 17:17:08
【问题描述】:

我有一个自定义 ListAdapter,它在 AsyncTask 中从 Internet 获取数据。

数据已完美添加到列表中,但是当我尝试执行操作时应用程序崩溃...

我确定这是因为我正在调用 notifyDataSetChanged();在错误的时间(即在 AsyncTask 结束之前)。

我现在得到了什么:

public class MyListAdapter extends BaseAdapter {
    private ArrayList<String> mStrings = new ArrayList<String>();

    public MyListAdapter() {
        new RetreiveStringsTask().execute(internet_url);
        //here I call the notify function ****************
        this.notifyDataSetChanged();
    }

    class RetreiveStringsTask extends AsyncTask<String, Void, ArrayList<String>> {
        private Exception exception;

        @Override
        protected ArrayList<String> doInBackground(String... urls) {
            try {
                URL url= new URL(urls[0]);
                //return arraylist
                return getStringsFromInternet(url);;
            } catch (Exception e) {
                this.exception = e;
                Log.e("AsyncTask", exception.toString());
                return null;
            }
        }

        @Override
        protected void onPostExecute(ArrayList<String> stringsArray) {
            //add the tours from internet to the array
            if(stringsArray != null) {
                mStrings.addAll(toursArray);
            }
        }
    }
}

我的问题是:我可以从 AsyncTask 中的 onPostExecute 函数调用 notifyDataSetChanged() 还是在 AsyncTask 获取数据的任何其他时间调用?

【问题讨论】:

    标签: java android android-asynctask listadapter baseadapter


    【解决方案1】:

    我可以从 onPostExecute 函数调用 notifyDataSetChanged() 异步任务

    是的,当doInBackground 执行完成时,您可以从onPostExecute 调用notifyDataSetChanged() 来更新适配器数据。这样做:

    @Override
    protected void onPostExecute(ArrayList<String> stringsArray) {
        //add the tours from internet to the array
        if(stringsArray != null) {
            mStrings.addAll(toursArray);
            // call notifyDataSetChanged() here...
             MyListAdapter.this.notifyDataSetChanged();
        }
    }
    

    【讨论】:

    • 这会清除列表并从头开始加载吗?这听起来不是很没有效率吗?我问是因为面临两难境地,我是否应该在自己的应用程序中使用类似的解决方案。
    【解决方案2】:

    onPostExecute() 中调用notifyDataSetChanged()

    @Override
            protected void onPostExecute(ArrayList<String> stringsArray) {
                //add the tours from internet to the array
                if(stringsArray != null) {
                    mStrings.addAll(toursArray);
    MyListAdapter.this.notifyDataSetChanged();
                }
            }
    

    【讨论】:

      【解决方案3】:

      您是否尝试过在ASyncTaskonPostExecute 方法中调用它。 onPreExecuteonPostExecute 用于更新 UI。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多