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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With