Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter the results of content resolver in android?

Tags:

android

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.

like image 615
maxsap Avatar asked Jan 28 '10 17:01

maxsap


People also ask

What does content resolver do in Android?

The Content Resolver behaves exactly as its name implies: it accepts requests from clients, and resolves these requests by directing them to the content provider with a distinct authority. To do this, the Content Resolver stores a mapping from authorities to Content Providers.

What does ContentResolver query () return?

ContentResolver. query() will return null in the following cases: If you try to pass column names which don't exist in the database (a very common case is when developers use constants as column names, because they look similar to columns). It is likely to be null because your URI argument is invalid.

What is the use of content resolver?

Accessing a provider. When you want to access data in a content provider, you use the ContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider .


1 Answers

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.

like image 151
Diego Torres Milano Avatar answered Sep 28 '22 06:09

Diego Torres Milano