从数据库android删除后更新ListView

时间:2012-01-05 23:46:41

标签: android listview

从数据库中删除后我的ListView没有更新,我发现stackoverflow上的方法不起作用,这是我填充列表的方法:

...
private ListView list;
ListAdapter adapter; (ListAdapter is a class from here i set the layout of a row)
...
...

protected void onCreate(Bundle savedInstanceState) {
     ...
     ...
      database info = new database(this);
  info.open();
  data = info.getData2();
  data2 = info.getData3();
  info.close();   
  list=(ListView)findViewById(R.id.list);   
  adapter=new ListAdapter(this, data , data2);
  list.setAdapter(adapter);
      registerForContextMenu(list);
      ...
      ...
 }

 ...
 ...
 public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        ...
        ...
        if(menuItemName.equals("Delete")){
        menuItemName = "2";
        Log.i(TAG,"Primul "+listItemName + " " + " al doilea " + listItemName2);
        database delete = new database(this);
        delete.open();          
    delete.deleteEntryFromList(listItemName,listItemName2);
    delete.close();
        //here i am suposed to do
            adapter.notifyDataSetChanged();
        //but it does not work
        }
 }

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您需要更新varibals中的数据data = info.getData2();和   data2 = info.getData3();然后你说adapter.notifiDataSetChanged它会更新你的listview

EDIT 回答

database delete = new database(this);
    delete.open();          
delete.deleteEntryFromList(listItemName,listItemName2);
delete.close();
     database info = new database(this);
info.open();
 data = info.getData2();
data2 = info.getData3();
info.close();
adapter.notifyDataSetChanged();

答案 1 :(得分:0)

我总是遇到通知方法的问题。最简单的解决方案:创建一个名为updateAdapter()的方法,用它替换notify调用并将其放入其中:

  private void updateAdapter(){
  database info = new database(this);
  info.open();
  data = info.getData2();
  data2 = info.getData3();
  info.close();   
  list=(ListView)findViewById(R.id.list);   
  adapter=new ListAdapter(this, data , data2);
  list.setAdapter(adapter);
      registerForContextMenu(list);
}   

调用而不是notify *方法。