1

我有一个扩展listactivity的活动,在这个类中扩展我有一个扩展baseadapter的类。

现在在我的列表活动中我有这个 onCreate

 /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
    setListAdapter(new BuildingAdapter(this));

    final ProgressDialog loading = new ProgressDialog(this);
    loading.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    loading.setTitle("Laddar");
    loading.setMessage("Hämtar data från servern");
    loading.show();

    new AsyncTask<Void, Void, DataPacket.Data>()
    {
        @Override
        protected DataPacket.Data doInBackground(Void... params){
            return ServerConnection.getBuildings();
        }

        @Override
        protected void onPostExecute(DataPacket.Data param) {
            ((MainenanceApplication)getApplication()).setDataStructure(param);
            loading.dismiss();
            //((BuildingAdapter)getListAdapter()).notifyDataSetChanged();
            setListAdapter(new BuildingAdapter(BuildingSelectionActivity.this));
        }

    }.execute();
}

这按预期工作,但我的问题是在 onPostExecute 我更新列表适配器使用的数据结构。为什么我不能只调用 notifyDataSetChanged ?

如果我有该行,则视图不会自行更新,但是如果我使用 setListAdapter 下的行,则一切正常。

4

3 回答 3

1

您是否尝试过为此使用AsyncTaskLoader而不是 AsyncTask。Loaders正是为这类东西而设计的。请注意,即使加载器在 API-10 之前不可用,您仍然可以通过API-4 及更高版本的 android Support Pacakge轻松访问它们。

于 2011-10-27T17:13:11.613 回答
1

如果适配器已经设置,再次设置它不会刷新列表视图。相反,首先检查列表视图是否有适配器,然后调用适当的方法。

我认为在设置列表视图时创建适配器的新实例并不是一个好主意。相反,创建一个对象。

BuildingAdapter adapter = new BuildingAdapter(context);

    if(getListView().getAdapter() == null){ //Adapter not set yet.
     setListAdapter(adapter);
    }
    else{ //Already has an adapter
    adapter.notifyDataSetChanged();
    }
于 2011-10-27T18:01:28.457 回答
0

唯一可以更新 UI 的地方是onProgressUpdate(...);. 从你的doInBackground(...),打电话publishProgress(...)

于 2011-10-27T17:18:08.103 回答