Asking Android for a contact
Listing 15.13 Pulling contact name out (CrimeFragment.java)
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
...
updateDate();
} else if (requestCode == REQUEST_CONTACT && data != null) {
Uri contactUri = data.getData();
// Specify which fields you want your query to return
// values for
String[] queryFields = new String[] {
ContactsContract.Contacts.DISPLAY_NAME
};
// Perform your query - the contactUri is like a "where"
// clause here
Cursor c = getActivity().getContentResolver()
.query(contactUri, queryFields, null, null, null);
try {
// Double-check that you actually got results
if (c.getCount() == 0) {
return;
}
// Pull out the first column of the first row of data -
// that is your suspect's name
c.moveToFirst();
String suspect = c.getString(0);
mCrime.setSuspect(suspect);
mSuspectButton.setText(suspect);
} finally {
c.close();
}
}
}
In Listing 15.13, you create a query that asks for all the display names of the contacts in the returned
data. Then you query the contacts database and get a Cursor object to work with. Because you know
that the cursor only contains one item, you move to the first item and get it as a string. This string
will be the name of the suspect, and you use it to set the Crime’s suspect and the text of the CHOOSE
SUSPECT button.
(The contacts database is a large topic in itself. We will not cover it here. If you would like to know
more, read the Contacts Provider API guide at developer.android.com/guide/topics/providers/
contacts-provider.html.)
Go ahead and run your app. Some devices may not have a contacts app for you to use. If that is the
case, use an emulator to test this code.