notifyDataSetChanged not updating ListView

丶灬走出姿态 提交于 2019-12-25 16:56:37

问题


I've read all the posts about this issue but I still can't get my ListView to update. I am extending ListActivity. Here's my ArrayAdapter:

 public List<String> songs = new ArrayList<String>();    
 public ArrayAdapter<String> allsongs;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    allsongs = new ArrayAdapter<String>(this,
            R.layout.song_items, songs);

 BindAllSongs();        
 ListView listView=getListView();
    registerForContextMenu(listView);
 }

now, when I delete a file I want the ListView to update:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    switch (item.getItemId()) {
        case R.id.delete_file:
            File file = new File(Environment.getExternalStorageDirectory().getPath() + "/AudioStreamRecorder/" + getListView().getAdapter().getItem(info.position).toString());
            file.delete();

            runOnUiThread(new Runnable() {
                public void run() {
                    allsongs.notifyDataSetChanged();    
                }
            });

            return true;
        case R.id.cancel:

            return true;
        default:
            return super.onContextItemSelected(item);
    }
}

In my BindAllSongs(); method:

public void BindAllSongs() {
 ...
 ...
setListAdapter(allsongs);
    }

This works great (the files are being deleted from sd card) but the list never updates. When I navigate away, then return to the ListView, the item is gone. (Returning to the ListView calls BindAllSongs(); again.) Thank you for any help, if you need more information let me know.


回答1:


The values in the ArrayAdapter are not actually tied to the file system. You need to call remove on the item(s) that gets deleted and THEN you can call notifyDataSetChanged (although you may not need to).



来源:https://stackoverflow.com/questions/12991411/notifydatasetchanged-not-updating-listview

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