Home > database >  Android room Database deletion not working
Android room Database deletion not working

Time:01-04

I am working with a Room DB for recycler view. And there is a delete icon on each row to delete that item. I want to delete same item from the Room db also. I have done below code but it's only reflecting in the list and after refresh that again load the deleted data from db.

Adapter class with delete listener:

btn_delete.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        deletePosition=getAdapterPosition();
        DeleteTask deleteTask = new DeleteTask();
        deleteTask.execute();
        alertDialog.dismiss();
    }
});
    
public class DeleteTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... integers) {
        DatabaseClient.getInstance(activity)
        .getAppDatabase()
        .DraftDataDao()
        .deleteById(deletePosition);
        return null;
    }
    
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        inProgressModelList.remove(deletePosition);
        notifyItemRemoved(deletePosition);
        notifyItemRangeChanged(deletePosition, inProgressModelList.size());
        globalData.setInprogress_count(inProgressModelList.size());
    }
}

Database Dao

@Query("DELETE FROM MovieData WHERE Id = :id")
public abstract void deleteById(int id);

Please help me on this.

CodePudding user response:

Position in the list will not equate to the correct id.

Position is 0 based, the first id assigned will be 1 unless you are specifically setting the first id assigned to 0 (unlikely) BUT progressively the correlation between position and id will get more and more convoluted.

If you click on the first item in the list, there will be nothing deleted if there is no row with an id set to 0.

Other rows will be out by 1 IF no rows have been deleted. If you then click to delete the 2nd item in the list, the position will be 1 and lets say the row with an id of 1 existed and was deleted then now the lowest id is 2. So now clicking the first or second item in the list will not result in a deletion. If the 3rd item is clicked and a deletion is made then now the lowest id is 3 ....

In short you need to get the actual id of the MovieData object that is at the position.

CodePudding user response:

Firstly, AsyncTask is now an obsolete class, I would recommend you look towards coroutines or rxjava.

Secondly, your adapter starts counting elements from 0. And in the database, if you have selected autoincrement of the primary key, report from 1. Perhaps because of this there is a problem

  •  Tags:  
  • Related