notifyDataSetChanged() on my adapter does not update the listview, why?

寵の児 提交于 2019-12-02 07:56:13

问题


I have a activity that extends listactivity, extended in this class i have a class that extends baseadapter.

now in my listactivity i have this 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();
}

This works as it's supposed to, but my question is in onPostExecute I update the datastructure that the list adapter uses. Why cant I just call notifyDataSetChanged ??

If I have that line the view does not update itself, but if I use the line under where I do setListAdapter, it all works.


回答1:


If the adapter is already set, setting it again will not refresh the listview. Instead first check if the listview has a adapter and then call the appropriate method.

I think its not a very good idea to create a new instance of the adapter while setting the list view. Instead, create an object.

BuildingAdapter adapter = new BuildingAdapter(context);

    if(getListView().getAdapter() == null){ //Adapter not set yet.
     setListAdapter(adapter);
    }
    else{ //Already has an adapter
    adapter.notifyDataSetChanged();
    }



回答2:


Have you tried using an AsyncTaskLoader instead of an AsyncTask for this. It's this kind of stuff that Loaders were exactly designed for. Note that even though Loaders weren't available until API-10 you can still easily access them via the android Support Pacakge from API-4 and up.




回答3:


The only place you can update the UI is in onProgressUpdate(...);. From your doInBackground(...), call publishProgress(...).



来源:https://stackoverflow.com/questions/7919691/notifydatasetchanged-on-my-adapter-does-not-update-the-listview-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!