Mewzer Mewzer - 2 months ago 7
Android Question

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

I am looking at the Android notepad application sample code in


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

// 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"

// 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"

I notice the projection map is used later in the

SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

* 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:

Why is this projection map needed?


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.