What is the purpose of an Android projection map in a content provider?

Mewzer picture Mewzer · Oct 5, 2012 · Viewed 9.9k times · Source

I am looking at the Android notepad application sample code in <path_to_SDK>/samples/android-16/NotePad/src/com/example/android/notepad.

I was wondering if anyone could explain to me why the following code is needed in NotepadProvider.java?

// Creates a new projection map instance. The map returns a column name
// given a string. The two are usually equal.
sNotesProjectionMap = new HashMap<String, String>();

// Maps the string "_ID" to the column name "_ID"
sNotesProjectionMap.put(NotePad.Notes._ID, NotePad.Notes._ID);

// Maps "title" to "title"
sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_TITLE,NotePad.Notes.COLUMN_NAME_TITLE);

// Maps "note" to "note"
sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_NOTE, NotePad.Notes.COLUMN_NAME_NOTE);

// Maps "created" to "created"
sNotesProjectionMap.put(NotePad.Notes.COLUMN_NAME_CREATE_DATE, NotePad.Notes.COLUMN_NAME_CREATE_DATE);

// Maps "modified" to "modified"
sNotesProjectionMap.put(
        NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE,
        NotePad.Notes.COLUMN_NAME_MODIFICATION_DATE)

I notice the projection map is used later in the query() method:

...
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
qb.setTables(NotePad.Notes.TABLE_NAME);

/**
 * Choose the projection and adjust the "where" clause based on URI pattern-matching.
 */
switch (sUriMatcher.match(uri)) {
    // If the incoming URI is for notes, chooses the Notes projection
    case NOTES:
    qb.setProjectionMap(sNotesProjectionMap);
    break;
...

Why is this projection map needed?

Answer

user picture user · Oct 9, 2012

The Notepad application from the SDK demos is a sample application, one that should be an example of API use and good practices using those APIs, that is why they probably use a projection map. Although the Notepad sample doesn't really need a projection map the use of one is a good showcase for more complex cases when one is needed. For example, if I remember right, the Shelves application written by one of the Google engineers is using a projection map in its ContentProvider and that projection map isn't just a simple mapping with identical key-value pairs.

I've also added a link to the documentation of the method SQLiteQueryBuilder.setProjectionMap which has some details on why you would need a projection map.