I'm implementing a custom ArrayAdapter<T>
, and I want to set the hasStableIds
to true. But the ids of my T items are Strings and the getItemId
method returns longs.
So, what I am currently doing is:
@Override
public boolean hasStableIds() {
return true;
}
@Override
public long getItemId(int position) {
return this.getItem(position).getId().hashCode();
}
Where getId()
returns a String.
Is this the correct solution for using String ids?
In particular, for this case, the String Ids are GUIDs, is there a better option?
You don't want to use the hashCode()
because this way, two different GUIDS might result in the same ID.
Just code a mapping. Something like this...
private static class GuidToIdMap {
private final Map<String, Long> guidToIdMapping = new HashMap<String, Long>();
private final Map<Long, String> idToGuidMapping = new HashMap<Long, String>();
private long idGenerator = 0;
public long getIdByGuid(final String guid) {
if ( ! guidToIdMapping.containsKey(guid)) {
final long id = idGenerator++;
guidToIdMapping.put(guid, id);
idToGuidMapping.put(id, guid);
}
return guidToIdMapping.get(guid);
}
public String getGuidById(final long id) {
if (idToGuidMapping.containsKey(id)) {
return idToGuidMapping.get(id);
}
return null;
}
}
private final GuidToIdMap guidToIdMap = new GuidToIdMap();
@Override
public boolean hasStableIds() {
return true;
}
@Override
public long getItemId(int position) {
final String guid = this.getItem(position).getId();
return guidToIdMap.getIdByGuid(guid);
}
// Use guidToIdMap.getGuidById(id) where the Android Framework passes you the generated id
Performance impact will be negligible....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With