Home > database >  Recycler view is not updating after deletion
Recycler view is not updating after deletion

Time:01-03

This is my code for deletion

public void onBindViewHolder(@NonNull final favAdapter.ViewHolder holder, int position) {
    holder.favText.setText(favlist.get(position).getPoetry());
    holder.delbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DataBaseHandler db= Room.databaseBuilder(holder.delbtn.getContext(),
                    DataBaseHandler.class, "room_db").allowMainThreadQueries().build();
            Dao_Class userDao= db.userDao();
            userDao.delete(favlist.get(position));

            favlist.remove(position);
            notifyItemRemoved(position);
        }
    });
    
}

I tried to get adapter position but I can not get.

CodePudding user response:

Instead of using position, you have to use holder.getAdapterPosition() to handle user clicks.

The ViewHolder provide us the getAdapterPosition which is always have the updated adapter’s position of this holder. It means that whenever you clicked on an item (ViewHolder item) we ask the adapter about it’s position. so you will get the latest position of this item in terms of Adapter’s logic.

CodePudding user response:

You have to remove item position and notify list by applying rangeChanged method

public void onBindViewHolder(@NonNull final favAdapter.ViewHolder holder, int position) {
    holder.favText.setText(favlist.get(position).getPoetry());
    holder.delbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DataBaseHandler db= Room.databaseBuilder(holder.delbtn.getContext(),
                    DataBaseHandler.class, "room_db").allowMainThreadQueries().build();
            Dao_Class userDao= db.userDao();
            userDao.delete(favlist.get(position));


            favlist.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, favlist.size());

        }
    });
    
}
  • Related