Skip to content Skip to sidebar Skip to footer

How To Delete Recycler View Item From Room Database

I am using MVVM architecture model to create an app.I have recycler view in MainActivity and on click of a delete button in recycler view item it should be removed from room databa

Solution 1:

Firstly, initialize UserViewModel in your adapter class like how you did in MainActivity, then call delete function.

holder.delete.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View view) {
             userModel.deleteItem(users);  
        }
    });

Add this function in UserModel class.

publicvoiddeleteItem(User user)= repo.deleteItem(user);

In UserRepository class, call Delete function.

public void deleteItem(User user) {
        userDb.userDao().Delete(user);
 }

Solution 2:

Try to observe changes form the database with live data, whenever you perform anything, adding or deleting(in the database), in your observer refresh that data for the recycler view

Set a click listener to your Adapter

publicinterfaceOnListInteractionListener {
        // TODO: Update argument type and namevoidonListInteraction(User user);
    }

In Adapter class

privatefinal OnListInteractionListener mListener;

    publicUserAdapter(List<User> users, OnListInteractionListener listener,Context context){

        mListener = listener;
    }

and in view bind holder

holder.delete.setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View view) {

mListener.onListInteraction(userList.get(position))
        }
    });

Implement that listener in your activity/fragment and from that, you can access Viewmodel and repo

Post a Comment for "How To Delete Recycler View Item From Room Database"