Search code examples
androidpositionadapter

How to delete items from Recycler View from another class?


I have a Recycler View inside Bottom Sheet , and if the item is clicked, it will be shown in Fragment.

Inside my Fragment i have a delete button (to delete item). How to call list.remove(position);?

Delete Button method :

buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view == buttonDelete){
                    switchCardAdapter.deleteMethod(1);
                }
            }
        });

1 only dummy position , how do i get a real position from adapter?

Delete Method inside Adapter :

public void deleteMethod(int position) {
        cards.remove(position);
    }

Full BindViewHolder method :

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int 
position) {
       final Card card = cards.get(position); 
       holder.textNumber.setText(String.valueOf(card.getNumberCard()));
       holder.textName.setText(card.getName());
       holder.itemView.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view) {
                Bundle b = new Bundle();
                b.putString("name", card.getName());
                b.putString("description", card.getDescripton());
                b.putString("type", card.getType());
                b.putLong("numberCard", card.getNumberCard());
                b.putInt("cvv",card.getCvv());
                b.putInt("exp", card.getExp());
                b.putInt("pin", card.getPin());
                cardFragment.setDataCard(b);
                bottomSheetFragment.dismiss();
        }
    });
}

public void deleteMethod(int position) {
    cards.remove(position);
}

Any help would be appreciated.


Solution

  • public void deleteMethod(int position) {
            cards.remove(position);
            adapter.notifyItemRemoved(position)
        }
    

    As per my understanding, your code flow should be like below:

    From one fragment you have open 1 bottom sheet that contains RV items. now when user clicks on RV item, You have open New fragment from "Card fragment" and dismissed bottom sheet. In new fragment you have passed bundle data. In card Fragment , you have delete button that will remove item from list of cards.

    So From your card fragment using interface, you have to notify to your first fragment from where you have open Bottom sheet. In this fragment you have to remove that particular item from list for cards. ( you have to pass position from card fragment to first fragment to delete from list ).

    Now your card list is updated. You can again open Bottom sheet with newly updated list. ( previously in onbindViewHolder, you have dismissed) .