删除项目后如何更新列表?

时间:2016-04-19 05:30:12

标签: android database list sqlite listview

我想从arrayList中删除一个项目,并在删除后更新它。查询正在执行删除操作,但列表未更新。 下面是onItemLongClickListener代码。

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            help.deleteEntry(position);
            adapter.remove(adapter.getItem(position));
            adapter.notifyDataSetChanged();

            Toast.makeText(Search.this, "Delete..", Toast.LENGTH_SHORT).show();
            return true;
        }
    });

删除DatabaseHelper的代码。

 public void deleteEntry(long id) {

    // delete row in user table based on id

    SQLiteDatabase db = this.getReadableDatabase();
    db.delete(TABLE_NAME,KEY_ID + " = " + id,null);

}

2 个答案:

答案 0 :(得分:3)

在适配器中编写一个方法来删除项目:

public removeItem(int position){
  yourArrayList.remove(position);
  notifyDataSetChanged();
}

从onItemLongClick列表视图中调用此方法:

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {


            adapter.removeItem(position);

        }
    });

答案 1 :(得分:0)

我注意到这里有两件事情,首先不要通过位置从数据库中删除行,因为id是自动增量,其次是删除你应该getWriteableDatabase()

所以你的代码应该是这样的

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Obj obj = adapter.getItem();
            help.deleteEntry(obj.getId());
            adapter.remove(adapter.getItem(position));
            adapter.notifyDataSetChanged();

            Toast.makeText(Search.this, "Delete..", Toast.LENGTH_SHORT).show();
            return true;
        }
    }); 

deleteEntry()中使用此

SQLiteDatabase db = this.getWriteableDatabase();