Getting a phone number from a search URI

I am trying to get a contact phone number using my URI for searching, but I cannot get it to work.

Cursor myC = getContentResolver().query(lookupURI, null, null, null, null); String phoneNumber; if (myC.moveToFirst()) { while (myC.moveToNext()) { phoneNumber = myC.getString(myC .getColumnIndex(Phone.NUMBER)); Log.v("t", "phone number is: " + phoneNumber); } } 

where lookupURI.toString() is the URI: content://com.android.contacts/contacts/lookup/0r1-304846522C3052482C4A3442423C3248/1

Does anyone know what I'm doing wrong?

+6
android uri cursor android-contacts
Dec 21 '11 at 19:06
source share
1 answer

I can not guarantee that this will work for 4.0, because I have not used it for a while, but it works fine on 2.3.3:

To get a contact, first I will ask the user to select a contact:

 public void clickSelectContact(View v) { Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI); startActivityForResult(i, CONTACTS_REQUEST_CODE); } 

When the user selects a contact, he returns to this method:

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == CONTACTS_REQUEST_CODE){ if(resultCode == RESULT_OK){ Uri uri = data.getData(); System.out.println("uri: "+uri); System.out.println("PHONE NUMBER: " + PhoneUtils.getContactPhoneNumber(this, uri.getLastPathSegment())); } } } 

Which calls my static util class:

 private static final String TAG = "PhoneUtils"; public static String getContactPhoneNumber(Context context, String contactId) { int type = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE; String phoneNumber = null; String[] whereArgs = new String[] { String.valueOf(contactId), String.valueOf(type) }; Log.d(TAG, "Got contact id: "+contactId); Cursor cursor = context.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone._ID + " = ? and " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?", whereArgs, null); int phoneNumberIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER); if (cursor != null) { Log.d(TAG, "Returned contact count: "+cursor.getCount()); try { if (cursor.moveToFirst()) { phoneNumber = cursor.getString(phoneNumberIndex); } } finally { cursor.close(); } } Log.d(TAG, "Returning phone number: "+phoneNumber); return phoneNumber; } 

Where contactId = lookupURI.getLastPathSegment ();

So hard for such a simple thing !: - (

Ps you may need this permission in your manifest:

  <uses-permission android:name="android.permission.READ_CONTACTS" /> 
+5
Dec 21 '11 at 19:11
source share



All Articles