Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adapter with hasStableIds using GUIDs or Strings as Ids

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?

like image 265
pomber Avatar asked Oct 02 '14 20:10

pomber


1 Answers

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....

like image 173
Niels Avatar answered Sep 27 '22 18:09

Niels