Marian Klühspies
Marian Klühspies

Reputation: 17627

Get contacts from SQL database by certain criteria on Android

How do I query all contacts matching a certain criteria on Android?

Let´s say, I want to have all contacts, which have a name, a phone number, but no profile picture.

As I understand the SQL thing, I need some kind of selection, which is passed to my query, but how would it exactly look in the example above?

I´m asking, because I´m currently running an app which first queries all contacts and after that I iterate through it and filter it, which seems much less performant then querying directly the right contacts

Upvotes: 0

Views: 890

Answers (1)

Emmanuel
Emmanuel

Reputation: 13223

You are correct in the sense that contacts are stored in a SQLite database, but they are accessed via the Contacts Content Provider.

The Contacts Content Provider is organized in a three table fashion. At the bottom of the data structure lies the Data table. Here you will find all data that pertains to a specific RawContact (will discuss shortly). The Data table stores information like phone numbers, emails, addresses,etc. It does so by using MIME name value pairs defined on the mimetypes database. Up one level is the RawContacts database. Here all the information that pertains to the same account (i.e. Contact John Doe may have a twitter and Facebook account). In short, the RawContacts table keeps track of Data MIME types that pertain to the same person so there is no need to store the same information multiple times for different accounts. At the top of the data structure you have the Contacts table that groups all the information for a single person. It is basically a way of unifying all account information into one contact. Think of this contacts as you regularly would.

You should take a look at the Loader class which will allow you to perform queries on a background Thread. If you use this class once you implement the Loader callback for the Cursor, you will create a CursorLoader. One of its constructors parameter is A typical MySQL where clause where you can specify the constraints you want to include as part of your query.

Here you would find a guide to Loaders to query a database.

Upvotes: 3

Related Questions