Tech Talk: Is that even English?
Sometimes when you walk the halls of HCSS, you’ll see employees riding hoverboards and hear the sounds of shooting NERF guns. And occasionally you’ll even hear what sounds like a completely foreign language being spoken.
This is true especially in our development department. Michael Nguyen, an android developer at HCSS, wanted to share this piece with all the other techies out there.
Retrofitting an Android Database with “_id”
Android SQLite is pretty much vanilla SQLite, but with one caveat: if you want to use ContentProviders, CursorAdapters, and other handy framework widgets, you will need to have a column named “_id”.
In most cases, this means your primary key should be “_id”. Unfortunately, at HCSS, our database wasn’t designed with “_id” in mind, so our primary keys are “id” or “ID”, somewhat inconsistently. To work around it, we needed to ensure that each content provider query returns a cursor containing an “_id” column.
Here’s how we did it.
/** Ensure queries have an "_id" field by aliasing the idField to “_id”. */
private String[] ensureProjection_id(String[] projection, String idField) {
if (projection == null) {
return new String[] {"*", idField + " AS _id"};
}
String[] newProjection = new String[projection.length + 1];
System.arraycopy(projection, 0, newProjection, 0, projection.length);
newProjection[projection.length] = idField + " AS _id";
return newProjection;
}
In ContentProvider.query, we simply replace the specified query projection with the result of the above method. Voila! Now the resulting cursors contain an “_id” column, and CursorAdapters work as expected.
Note that aliasing _id should only be done if the original query projection contains the idField. .Imagine something like ‘SELECT DISTINCT firstName FROM person’. If _id is aliased, we would get repeated names, since DISTINCT would also consider the _id in determining if a record is distinct.
Did you get that?
Michael loves material design, open source, and thinks android O should be named “Oreo”.