Android Tutorial

(avery) #1
Android Tutorial 337

String email = primaryEmail.getString(0);
primaryNumber.moveToFirst();
String number = primaryNumber.getString(0);


If an email or phone number doesn’t exist, an exception called
android. database. Cursor IndexOut OfBounds Exception is thrown.
This can be caught, or you can check to see that a result was
actually returned in the Cursor first.

Querying for a Specific Contact

If that seemed like quite a lot of coding to get a phone number,
you’re not alone. For getting a quick piece of data, there is a faster
way. The following block of code demonstrates how we can get the
primary number and name for one contact. The primary number for
a contact is designated as the default number within the contact
manager on the handset. It might be useful to use the primary
number field if you don’t get any results back from the query.

String[] requestedColumns = {
Contacts.Phones.NAME,
Contacts.Phones.NUMBER,
};
Cursor contacts = managedQuery(Contacts.Phones.CONTENT_URI,
requestedColumns, Contacts.Phones.ISPRIMARY + “<>0”,
null, “name desc limit 1”);
Log.d(debugTag, “Contacts count: “ + contacts.getCount());
int nameIdx = contacts.getColumnIndex(Contacts.Phones.NAME);
int phoneIdx = contacts.getColumnIndex(Contacts.Phones.NUMBER);
contacts.moveToFirst();
Log.d(debugTag, “Name: “ + contacts.getString(nameIdx));
Log.d(debugTag, “Phone: “ + contacts.getString(phoneIdx));


This block of code should look somewhat familiar, yet it is a much
shorter and more straightforward method to query for phone
numbers by Contact name. The Contacts. Phones. CONTENT _URI
Free download pdf