Monday, August 16, 2010

Android Activity.managedQuery selection and selectionArgs arguments

Most of the examples of managedQuery don't use the selection and selectionArgs arguments, others are pretty simple like :

Cursor simple(String id) {
return managedQuery(getIntent().getData(), PROJECTION,
 "id = " + id, null, DEFAULT_SORT_ORDER);
}

or

Cursor simple(String id) {
return managedQuery(getIntent().getData(), PROJECTION,
 "id = ?", new String [] ={id}, DEFAULT_SORT_ORDER);
}
Both of the above do exacly the same thing.
The '?'s are the elements in the array in order they are placed. [Resource]

I was working on a piece of code that stored IDs in SharedPreferences and then loaded the elements with those IDs into a ListView from a ContentProvider.

Basically I was trying to get that :
WHERE id IN ( id1, id2, id3, id4,...)

So the selection argument looked like that :
"id IN ( ? " +  [",? "] + " )"
and the selection args stored the ID of elements I wanted to load.

SharedPreferences data = getSharedPreferences("elementList",0);
Map <String, Integer> map = (Map<String, Integer>)data.getAll();
if (map.size() == 0) {
    return;
}
int i = 0;
Iterator it = map.entrySet().iterator();
String str [] = new String [map.size()];
while ( it.hasNext() ) {
    Map.Entry<String,Integer> pair
        = (Map.Entry<String,Integer>)it.next()
    str[i++] = pair.getKey();
    Log.i(this.getLocalClassName(), "pair key " + str[i-1]);
}
String whereClause = Prod._ID + " IN ( ?";
if (map.size()>1) {
    for (int j = 1 ; j < map.size(); ++j) {
        whereClause+=", ?";
    }
}
whereClause+=")";
Log.i(this.getLocalClassName(), whereClause);
Cursor cursor = managedQuery(getIntent().getData(), PROJECTION,
    whereClause , str, DEFAULT_SORT_ORDER);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
    this, R.layout.element_list_item,
    cursor, new String[] { NAME, DETAILS},
    new int[] { android.R.id.text1, android.R.id.text2 }
);
elemList.setAdapter(adapter);

Hope that not-that-trivial example make this topic more clear. If you would like to know more about ContentProviders or managedQuery I suggest you try this or the Notepad Tutorial.

No comments:

Post a Comment