1

I am using android.support.v7.util.SortedList to bind data on RecyclerView. Everything works fine except that when I tried updating data, indexOf(obj) always returns -1.

private int findItem(ZoneContactLoaderAdapter mAdapter, ContactModel contactModel) {

//        int index = Collections.binarySearch(mAdapter.getContactModel(), contactModel, new BinarySearchWithComparator());
        return mAdapter.getContactModel().indexOf(contactModel);
    }

The logic is like this :

 int position = findItem(zoneContactLoaderAdapter, notificationContactModel);
if (position < 0) {

                        ContactModel adapterContactModel = new ContactModel(conversationID, Constants.ACCOUNT_TYPE, conversationName, "", null, conversationName, conversationID, false);
                        updateAdapterModel(adapterContactModel, notificationContactModel);
                        zoneContactLoaderAdapter.getContactModel().add(adapterContactModel);

                    } else {
                        notificationContactModel.setIsConversation(true);
                        ContactModel adapterContactModel = zoneContactLoaderAdapter.getItem(position);
                        updateAdapterModel(adapterContactModel, notificationContactModel);
                        zoneContactLoaderAdapter.getContactModel().updateItemAt(position, adapterContactModel);
                    }

The position always returns -1 and duplicate the data. Tried out solution from this thread , it still doesn't work fine. So, I thought of implementing custom binary search on the list itself using this as an example. But collection only takes List.

What better way can I find index of item on android.support.v7.util.SortedList. Thanks

Community
  • 1
  • 1
Belvi Nosakhare
  • 3,107
  • 5
  • 32
  • 65

1 Answers1

3

SortedList's indexOf method is very much dependent on the contained object's proper implementation of the hashCode() and equals() methods.

Leaving the default Object implementations is pretty much guaranteed to not work in your situation.

You can implement them yourself, you can choose to have Android Studio generate the methods for you, or you can use Project Lombok's @EqualsAndHashCode annotation to generate them at compile time. There are probably other options out there too - these are the ones that come to mind first.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67