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!

giorgiline
  • 1,271
  • 4
  • 21
  • 35

2 Answers2

21

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.

rui.araujo
  • 9,597
  • 1
  • 18
  • 24
  • 1
    Wow, simple and easy solution. Thanks! – giorgiline Apr 22 '12 at 14:30
  • 8
    hashCodes are not unique and default implementation uses position as id. How hashCode relates to item identifiers? – Petr Gladkikh Apr 22 '13 at 12:53
  • @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. – Andrea Richiardi Jan 04 '14 at 22:09
  • 1
    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. – Petr Gladkikh Jan 09 '14 at 07:20
  • @PetrGladkikh he said: "or has some kind of id field". Though `hashCode` is much weaker than an ID in the data, I agree. – TWiStErRob Nov 28 '14 at 12:56
  • 7
    It's final now. so cannot override it anymore. Has to call setHasStablesIds – Happy Dev Apr 11 '18 at 03:47
5

Add this in your adapter:

init {    
    setHasStableIds(true)
}

override fun getItemId(position: Int): Long = position.toLong()