How to filter the results of content resolver in android?

android

Solution

Instead of

getContentResolver().query(People.CONTENT_URI, null, null, null, null); 

you should use something like

final ContentResolver resolver = getContentResolver();
final String[] projection = { People._ID, People.NAME, People.NUMBER };
final String sa1 = "%A%"; // contains an "A"
cursor = resolver.query(People.CONTENT_URI, projection, People.NAME + " LIKE ?",
   new String[] { sa1 }, null);

this uses a parameterized request (using ?) and provides the actual values as a different argument, this avoids concatenation and prevents SQL injection mainly if you are requesting the filter from the user. For example if you are using

cursor = resolver.query(People.CONTENT_URI, projection,
   People.NAME + " = '" + name + "'",
   new String[] { sa1 }, null);

imagine if

name =  "Donald Duck' OR name = 'Mickey Mouse") // notice the " and '

and you are concatenating the strings.

Problem

I would like to get user contacts and then append some kind of regular expression and append them to a list view. I am currently able to get all the contacts via `getContentResolver().query(People.CONTENT_URI, null, null, null, null);` and then pass them to a custom class that extends `SimpleCursorAdapter`. So I would like to know how to get only the contacts that match a regular expression and not all of users contacts.

Original source