Search code examples
androidandroid-intentandroid-contentprovidermime-typesandroid-contacts

Retrieveing saved address from phonebook by using a pick intent


I want to pick a contact from phone book using intent and selected contact should also contain respective city and state (if saved by user).

Here is what I am trying for past few days:

private void accessContacts() {
 Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
    intent.setDataAndType(ContactsContract.Contacts.CONTENT_URI,
        ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
    startActivityForResult(intent, PICK_CONTACT);
  } 

@Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
      case PICK_CONTACT:
        if (resultCode == Activity.RESULT_OK) {
          Uri contactData = data.getData();
          String[] projection = {
              ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
              ContactsContract.CommonDataKinds.Phone.NUMBER
          };
          String name = null;
          String phoneNumber = null;
          String city = null;
          String state = null;

          Cursor c =
              getActivity().getContentResolver().query(contactData, null, null, null, null);
          if (c != null) {
            if (c.moveToFirst()) {
              int nameIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
              int phoneNumberIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
              name = c.getString(nameIdx);
              phoneNumber = c.getString(phoneNumberIdx);

              String id = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup._ID));

              String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND "
                  + ContactsContract.Data.MIMETYPE + " = ?";
              String[] addrWhereParams = new String[]{id,
                  ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
              Cursor addrCur = getActivity().getContentResolver()
                  .query(ContactsContract.Data.CONTENT_URI,
                  null, addrWhere, addrWhereParams, null);

              if (addrCur.moveToFirst()) {
                city = addrCur.getString(
                    addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
                state = addrCur.getString(
                    addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
              }
              addrCur.close();

            }
            c.close();
          }

          if (name == null) {
            name = "No Name";
          }

          if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() < 10) {
            handleAddConnectionError(getContext().getString(R.string.invalid_phone_number));
            return;
          }

          Phonenumber.PhoneNumber number =
              Utils.validateMobileNumber2(phoneNumber, Device.getCountryCode(getActivity()));
          if (number == null) {
            handleAddConnectionError(getContext().getString(R.string.invalid_phone_number));
            return;
          }


          this.moveToCategoryPage(name, String.valueOf(number.getNationalNumber()),
              Utils.getCountryCodeWithPlusSign(number), false, null,
              city, state);
        }
        break;
    }

  }

While removing/changing this:

intent.setDataAndType(ContactsContract.Contacts.CONTENT_URI, ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);

it throws exception.

How can I get saved address from pick intent?


Solution

  • There's one big bug that I can see here:

    String id = c.getString(c.getColumnIndex(ContactsContract.PhoneLookup._ID));
    

    You shouldn't use PhoneLookup.XXX columns when querying over Phone.CONTENT_URI, this code actually returns the Phone._ID column instead (because both have the same const string name), which is NOT a contactID, it is a specific phone's ID (or a Data._ID). You also can't access columns from a cursor that you didn't specify in your projection.

    So change you projection to:

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

    and replace that line with:

    Long contactId = c.getLong(2);
    

    Another thing you can do is to simplify your second query by querying over StructuredPostal.CONTENT_URI like this:

    String addrWhere = StructuredPostal.CONTACT_ID + " = " + contactId;
    Cursor addrCur = getActivity().getContentResolver().query(StructuredPostal.CONTENT_URI, null, addrWhere, null, null);
    

    Please note that unlike your first query for the Phone.NUMBER info, you app needs READ_CONTACTS permission to do the second query for the address, this is because you ask for a phone-picker intent which grants your app a temp. permission to access the picked phone number only from the contacts API, anything other then that requires permission.