0

I am implementing a swipe to delete with a RecyclerView and an ItemTouchHelper. Within my onSwiped function, I call my service to delete the element with an API request, but for that I need the adapter to give me the id of the element. I overrided the getItemId() function of my Adapter

@Override
public long getItemId(int position) {
   return dataSet.get(position).getId();
}

However when I am using it in my onSwiped function

@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
     AddBaseService addBaseService = AddBaseService.sharedInstance();
     long baseId = viewHolder.getItemId(viewHolder.getAdapterPosition());
     addBaseService.deleteBase(String.valueOf(baseId));

I got an error at the getAdapterPosition line saying

getItemId() in ViewHolder cannot be applied to (int)

although getAdapterPosition is supposed to return an int :/

user54517
  • 2,020
  • 5
  • 30
  • 47

2 Answers2

1

EDIT:

Here are two links that might help you solve your issue :


OP used : adapter.getItemId(viewHolder.getAdapterPosition()); instead of viewHolder.getItemId() to solve his problem.

Biscuit
  • 4,840
  • 4
  • 26
  • 54
  • My problem is not about how to set in an adapter to swipe and delete. I know how to do that and it works. The only problem that I have is about getting the id of the item. For some reasons it seems that it doesn't call the function. It always returns -1 – user54517 Mar 25 '20 at 13:41
  • 1
    In that case there is a few subject on SO that might help you, such as https://stackoverflow.com/questions/6711592/what-is-the-intent-of-the-methods-getitem-and-getitemid-in-the-android-class-bas and https://stackoverflow.com/questions/41919116/how-to-get-id-of-the-items-in-recyclerview – Biscuit Mar 25 '20 at 13:47
0

i think viewHolder.getItemId() expects long not int

moumenShobakey
  • 426
  • 5
  • 14
  • I tried with a long and I got the same message `getItemId() in ViewHolder cannot be applied to (long)` – user54517 Mar 25 '20 at 11:37
  • hey , i think you meant viewHolder.setItemId() :/ because viewHolder.getItemId does't expect anything actually :D – moumenShobakey Mar 25 '20 at 11:40
  • I tried that way first, but for some reasons, it always returns `-1` and when I put a breakpoint in my function getItemId() it seems that it is never called :/ – user54517 Mar 25 '20 at 11:51
  • Maybe you pass the id of the view after you delete it so it never exists , i didn't implement swip-delete before but if you want a way to find views use tags better – moumenShobakey Mar 25 '20 at 11:54