从数据库中删除后如何消除每个元素?

时间:2018-01-09 19:42:13

标签: android sqlite

我有一个数据库app.I想删除它后让每个项目从主屏幕消失。它会在长按后被删除,但在退出应用程序后再次进入后会变为不可见。那么,长按后如何立即从主屏幕上消失每个项目?

以下是我删除每个项目的代码段----

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        FriendsDbHelper fdb = new FriendsDbHelper(MainActivity.this);
        SQLiteDatabase db = fdb.getWritableDatabase();
        db.delete(TABLE_NAME,_ID+"=?",new String[]{Long.toString(id)});

        return true;
    }
});

2 个答案:

答案 0 :(得分:1)

当你似乎使用光标适配器(,即你根据id 删除)时,你需要

  • a)重新构建Cursor然后
  • b)使用适配器的swapCursornotifyDataSetChanged方法。
  

请注意!如果您没有使用光标适配器,那么您可能会   如果您使用传递给的 id ,则会遇到问题   setOnItemLongClickListener方法,因为这不一定是   行的id但它与position的值相同。起初它   似乎工作但可能开始删除错误的行或   不删除任何行。

你的代码将是: -

listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        FriendsDbHelper fdb = new FriendsDbHelper(MainActivity.this);
        SQLiteDatabase db = fdb.getWritableDatabase();
        db.delete(TABLE_NAME,_ID+"=?",new String[]{Long.toString(id)});
        mycursor = fdb.your_method_to_get_the_cursor(); //<<<< will need changing
        your_adapter.swapCursor(mycursor); //<<<< will need changing
        return true;
    }
});

这是一个有效的例子: -

// Get the ListView according to it's id
imagelist = (ListView) findViewById(R.id.imagelist);
// Get the Cursor
images = imgdbhlpr.getAllImages();
// Instantiate the Cursor Adapter
sca = new SimpleCursorAdapter(this,
        android.R.layout.simple_list_item_1,
        images,
        new String[]{ImgDBHelper.DSCR_COL},
        new int[]{android.R.id.text1},
        0
);
//
imagelist.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        imgdbhlpr.deleteImageRow(id);
        images = imgdbhlpr.getAllImages();
        sca.swapCursor(images);
        return true;
    }
});
imagelist.setAdapter(sca);

答案 1 :(得分:0)

您需要将其从listView中删除。您需要调用列表适配器,然后调用方法notifyDataSetChanged()

相关问题