Mirko Marchiori Mirko Marchiori - 3 months ago 22
Android Question

Android - back from Contacts intent without selecting one

In my android application I have a list of people (name and telephone number) and I let the user add a person to the app's database by importing one from their contacts list. Everything works fine, but a user could click the button to import a new person and then go back, so the Contacts intent will be closed without actually selecting a contact.

So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.

private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();

String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};

Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();

// Retrieve the name from the DISPLAY_NAME column
String name = cursor.getString(cursor.getColumnIndex(ontactsContract.Contacts.DISPLAY_NAME));

// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);

// update database
dbManager.addPerson(name, number, true);
}
}

}


So how can I check if the user actually selected a contact or went back?

Answer

So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.

You already have the code for this: if (resultCode == RESULT_OK). If the user presses BACK, you will not get RESULT_OK.

Comments