Android: How to make an adapter with stable ids?
Asked Answered
P

2

15

I've made my own custom adapter extended from BaseAdapter to show a listview and so on...

I want it to support single and multi selection, so it must have stable ids. I've checked with the ADAPTER.hasStableIds() and the result is false.

I've overrided this method to do try to get stables ids with no luck.

public long getItemId(int position) {
   return (long) getItem(position).hashCode();
}

Any idea how to make it? thanks!

Prepossessing answered 22/4, 2012 at 11:56 Comment(0)
C
22

Override hasStableIds to return true.

Also the data on your adapter must either override hashCode() or has some kind of id field to be returned on getItemId.

Caliph answered 22/4, 2012 at 12:9 Comment(6)
Wow, simple and easy solution. Thanks!Prepossessing
hashCodes are not unique and default implementation uses position as id. How hashCode relates to item identifiers?Bout
@Petr: From what I understood "Stable Ids" means that you are always able to identify your objects/rows using a unique number (aka the Ids never change during the life-cycle of your adapter). Therefore, in the same way you need unique/not clashing hashCodes for HashMap, you can reuse the hashCode here in your Adapter.Allopathy
Hash codes are not guaranteed to be unique. Uniqueness of hash codes within same hash table (e.g. HashMap) is desirable property but not a requirement. I still believe that overriding hashCode() is unnecessary in this case.Bout
@PetrGladkikh he said: "or has some kind of id field". Though hashCode is much weaker than an ID in the data, I agree.Clarindaclarine
It's final now. so cannot override it anymore. Has to call setHasStablesIdsBlen
F
5

Add this in your adapter:

init {    
    setHasStableIds(true)
}

override fun getItemId(position: Int): Long = position.toLong()
Finesse answered 6/3, 2022 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.