简体   繁体   中英

android delete item from database but not form list view

I have an custom list view with data from my database. In my list adapter I set an onlongclicklistener to delete an item in my database:

row.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            AlertDialog alertDialog = new AlertDialog.Builder(context).create();
            alertDialog.setTitle(context.getResources().getString("TITEL"));

            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "NO",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "YES",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            String delete = "DELETE FROM "+DatabaseHelper.DATABASE_TABLE+" " +
                                    "WHERE "+DatabaseHelper.COLUMN_ID+" = "+databaseListItems.getID();

                            sqlHandler = new DatabaseHandler(context);
                            sqlHandler.executeQuery(delete);

                            dialog.dismiss();
                        }
                    });

            alertDialog.show();
            return false;
        }
    });

Item will be deleted in database, but not in list view. If I reload my list view, the item will disappear How can I reload my list view after deleting?

You should follow two steps:

1) When you confirm the delete, you have to remove the item from the object that you use in the adapter to fill the list

2) Then, you have to call notifyDatasetChanged()

If you don't delete the item from the adapter, it will be loaded again in the list calling notifyDatasetChanged()

After executing the Database query , delete the item from the arraylist which you are using to populate the listview by using this

myList.delete(position);

and call

notifyDatasetChanged();

for getting the item position , you can set setOnItemLongClickListener on listview.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM