0

I'm trying to get the phone number of a specific contact. I can get the contact name, but somehow, I have an error when I try to get the phone number.

I have put the permission in my androidManifest.xml : <uses-permission android:name="android.permission.READ_CONTACTS" />

And when I run the following code : `ContactInfo contactInfo = null;

    String[] projection = {
            ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER
    };
    try (Cursor cursor = getContentResolver().query(contactUri, null, null, null, null)) {

        if (cursor != null && cursor.moveToFirst()) {

            String[] columnNames = cursor.getColumnNames();

            for (int i = 0; i < columnNames.length; i++) {
                Log.d("Info SMS", "Column " + i + ": " + columnNames[i] + ", value :" + cursor.getString(i));
            }

            int idIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
            int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY);
            int phoneNumberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

            Log.d("Info SMS", "ID Index : " + String.valueOf(idIndex));
            Log.d("Info SMS", "Name Index : " + String.valueOf(nameIndex));
            Log.d("Info SMS", "Phone Index : " + String.valueOf(phoneNumberIndex));
            Log.d("Info SMS", "Index okay");

            String name = cursor.getString(nameIndex);
            Log.d("Info SMS Name", "Name :" + name);

            String phoneNumber = cursor.getString(phoneNumberIndex);
            Log.d("Info SMS", phoneNumber);

            contactInfo = new ContactInfo(name, phoneNumber);
        }
    } catch (Exception e) {
        Log.d("Info SMS Error", Arrays.toString(e.getStackTrace()));
    }

    Log.d("Info SMS", String.valueOf(contactInfo));
    return contactInfo;`

I have an error :

[android.database.CursorWindow.nativeGetString(Native Method), android.database.CursorWindow.getString(CursorWindow.java:465), android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:54), android.database.CursorWrapper.getString(CursorWrapper.java:141), fr.e1k.sms_sender.MainActivity.retrieveContactInfo(MainActivity.java:142), fr.e1k.sms_sender.MainActivity.lambda$onCreate$0$fr-e1k-sms_sender-MainActivity(MainActivity.java:60), fr.e1k.sms_sender.MainActivity$$ExternalSyntheticLambda0.onActivityResult(Unknown Source:4), androidx.activity.result.ActivityResultRegistry.doDispatch(ActivityResultRegistry.java:418), androidx.activity.result.ActivityResultRegistry.dispatchResult(ActivityResultRegistry.java:375), androidx.activity.ComponentActivity.onActivityResult(ComponentActivity.java:793), androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:164), android.app.Activity.dispatchActivityResult(Activity.java:8628), android.app.ActivityThread.deliverResults(ActivityThread.java:5316), android.app.ActivityThread.handleSendResult(ActivityThread.java:5362),android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:67), android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45), android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135), android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95), android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307), android.os.Handler.dispatchMessage(Handler.java:106), android.os.Looper.loopOnce(Looper.java:201), android.os.Looper.loop(Looper.java:288), android.app.ActivityThread.main(ActivityThread.java:7872), java.lang.reflect.Method.invoke(Native Method), com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548), com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)]

And the error is on this line : String phoneNumber = cursor.getString(phoneNumberIndex);

Because the phoneNumberIndex is Phone Index : -1.

I know this information thanks to these lines :

int phoneNumberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
Log.d("Info nbSMS", "Phone Index : " + String.valueOf(phoneNumberIndex));

And indeed, with this loop and logcat :

String[] columnNames = cursor.getColumnNames();
    for (int i = 0; i < columnNames.length; i++) {
                    Log.d("Info nbSMS", "Column " + i + ": " + columnNames[i] + ", value :" + cursor.getString(i));
    }

I only have access to the following information on the contact :

Column 0: last_time_contacted, value :0
Column 1: phonetic_name, value :null
Column 2: custom_ringtone, value :null
Column 3: contact_status_ts, value :null
Column 4: pinned, value :0
Column 5: photo_id, value :null
Column 6: photo_file_id, value :null
Column 7: contact_status_res_package, value :null
Column 8: contact_chat_capability, value :null
Column 9: contact_status_icon, value :null
Column 10: display_name_alt, value :Test
Column 11: sort_key_alt, value :Test
Column 12: in_visible_group, value :1
Column 13: starred, value :0
Column 14: contact_status_label, value :null
Column 15: phonebook_label, value :T
Column 16: is_user_profile, value :0
Column 17: has_phone_number, value :1
Column 18: display_name_source, value :40
Column 19: phonetic_name_style, value :0
Column 20: send_to_voicemail, value :0
Column 21: lookup, value :0r1-50324E50
Column 22: phonebook_label_alt, value :T
Column 23: contact_last_updated_timestamp, value :1692316538974
Column 24: photo_uri, value :null
Column 25: phonebook_bucket, value :20
Column 26: contact_status, value :null
Column 27: display_name, value :Test
Column 28: sort_key, value :Test
Column 29: photo_thumb_uri, value :null
Column 30: contact_presence, value :null
Column 31: in_default_directory, value :1
Column 32: times_contacted, value :0
Column 33: _id, value :1
Column 34: name_raw_contact_id, value :1
Column 35: phonebook_bucket_alt, value :20

There is nothing about the phone number.

I read the offical documentation, but it didn't help me that much. (https://developer.android.com/training/contacts-provider/retrieve-details).

I also checked this topic : Android get phone number from contact list But it didn't work for me.

I also had a look at this old topic : Getting Contact Phone Number

And I try to arrange it like that :

if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    Cursor pCur = getContentResolver().query(contactUri,null,ContactsContract.CommonDataKinds.Phone._ID +" = ?", new String[]{cursor.getString(idIndex)}, null);
                    String phone = cursor.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    Log.d("Info nbSMS", "Phone Number: " + phone);
                }

`

But still the same error.

I also had a look at some other old topic on stack overflow but still the same thing...

So I might be missing something. Do you have any idea of what is the source of all my problems ?

This is my first post on stackoverflow, so I might have missed some crucial information you need. Please tell me what is missing. Or maybe I didn't understand one of the solution I have found.

Thanks for your time.

e1k
  • 1
  • 2

2 Answers2

0

You also need the permission:

<uses-permission android:name="android.permission.READ_CALL_LOG"/>

else the query fails to fill the number field. Not on all devices, but on quite some.

  • Hello Johannes, thanks for your proposition but it doesn't change anything for me. – e1k Aug 20 '23 at 22:15
0

Well, let's try it differently. This is part of my code, which does not bother with contracts and numeric indexes:

Uri uri = Uri.parse("content://sms/inbox");    
cursor = resolver.query(
                    uri,
                    new String[]{"_id", "address", "body"},
                    null,
                    null,
                    "_id ASC");

@NotNull
private SMS buildSMS(@NotNull Cursor cursor)
{
    SMS sms = new SMS();
    sms.setId(cursor.getInt(cursor.getColumnIndexOrThrow("_id")));
    sms.setAddress(cursor.getString(cursor.getColumnIndexOrThrow("address")));
    sms.setBody(cursor.getString(cursor.getColumnIndexOrThrow("body")));
    //sms.setTime(cursor.getString(cursor.getColumnIndexOrThrow("date")));

    return sms;
}

Does this work?