2011-04-06 64 views
1

我有一个ListAdapter这是用来显示在Listview列表。现在我添加了一个longpress菜单操作来删除任何选定的项目。Android的ListAdapter没有更新

public boolean onContextItemSelected(MenuItem item) { 

     AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item 
       .getMenuInfo(); 
     final Long wordId = menuInfo.id; 
     // selected_row = menuInfo.position; 

     // To get the id of the clicked item in the list use menuInfo.id 
     switch (item.getItemId()) { 
     case CONTEXT_DELETE: 
      deleteRes(wordId); // delete function for the item 
      break; 
     default: 
      return super.onContextItemSelected(item); 

     } 
     //((BaseAdapter) favAdapter).notifyDataSetChanged(); 
     return true; 
    } 

但是在删除后,列表正在更新并显示带有已删除项目的旧列表。我尝试使用notifyDataSetChanged(),但它不起作用。概率的解决方案是什么?

+0

你确定底层的数据是通过'deleteRes(wordId);'来删除吗? – xandy 2011-04-06 06:22:04

+0

数据正在被正确删除......如果我去另一个区域......并回到那个区域......它会给出正确的列表。 – 2011-04-06 06:33:38

+0

也许你可以发布更多的代码,比如适配器,看看有什么问题。 – xandy 2011-04-06 07:41:19

回答

1

我用下面的代码和问题是解决了。

favCursor = wordDataHelper.getCursorFav(); 
((SimpleCursorAdapter) favAdapter).changeCursor(favCursor); 
+0

请详细说明你是如何解决这个问题的?我有同样的问题。我已经发布我的代码在http://stackoverflow.com/questions/23512776/listview-not-upadated-properly-after-deletion-in-android-fragment。谢谢。 – user2011302 2014-05-09 03:19:11

0

从数组/列表中删除项目,然后将数组/列表分配给适配器,然后写入notifyDataSetChanged()。

+0

没有数组或列表。它是一个Cursor,它提供给favAdapter(它是一个ListAdapter),使用“ListAdapter favAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,favCursor,new String [] {WordDataHelper.ENGWORD},new int [ ] {android.R.id.text1});“ – 2011-04-06 06:38:03

0

从列表中删除项目后,必须通过对数据库执行新查询来获取新的游标。然后,您可以通过以新光标作为参数调用changeCursor()来更改SimpleCursorAdapter(CursorAdapter)的光标。

0

使用getListView()。invalidateViews删除后。

0
  1. 从数据库查询
  2. 删除该项目得到一个新的光标,或者重新查询旧adapter.getCursor().requery()
  3. 呼叫adapter.notifyDatasetChanged
+0

我认为不应该使用repery()。 – Flo 2011-04-06 17:28:09

+0

就这样。无论如何,从未使用过它。 – 2011-04-06 17:40:11

0

尝试使用notifyDataSetChanged方法,它应该工作。

adapter.notifyDataSetChanged(); 

但是,有时会失败。如果它失败了,那么用新的列表元素重新初始化该章节。这个对我有用。

adapter = new ArrayAdapter<Item>(getApplicationContext(),android.R.layout.simple_list_item_1, itemList); 
setListAdapter(adapter);