Как прочитать номер телефона в Android из контактов?

#android #contacts #android-contentprovider

#Android #Контакты #android-contentprovider

Вопрос:

Я перепробовал несколько комбинаций, но при поиске номера телефона отображается ошибка, вот мой код:

 public void readPhoneLookUp(){
        Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        //people.moveToFirst();
        while(people.moveToNext()) {
               int nameFieldColumnIndex = people.getColumnIndex(PhoneLookup.DISPLAY_NAME);
               String contact = people.getString(nameFieldColumnIndex);
               Log.i(LOG, "Contacts: "  contact);
               int numberFieldColumnIndex = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
               String number = people.getString(numberFieldColumnIndex);
               Log.i(LOG, "Number: "  number);
            }
    }//readPhoneLookUp ends
  

Я также добавил разрешение READCONTACTS в манифест
Я также пробовал это :

 public void readContactsNew(){
        ArrayList<String> contactListArrLst = null;
        contactListArrLst = new ArrayList<String>();

        ArrayList<String> contactNumberArrLst = null;
        contactNumberArrLst = new ArrayList<String>();

        ContentResolver contentResolver = getContentResolver();

        Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
        int curCount = cursor.getCount();
        Log.i(LOG, "Contacts:Count  "  curCount);
        cursor.moveToFirst();
        while(!cursor.isAfterLast()){
            contactListArrLst.add(cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME)));
            contactNumberArrLst.add(cursor.getString(cursor.getColumnIndex(PhoneLookup.NUMBER)));
            cursor.moveToNext();
        }
        cursor.close();
        Log.i(LOG, "Contacts: "  contactListArrLst);
        Log.i(LOG, "ContactNumber: "  contactNumberArrLst);
  

Но выдает ошибку в contactNumberArrLst

Это ошибка в журнале Cat:

 11-11 10:39:44.231: ERROR/AndroidRuntime(1683): FATAL EXCEPTION: main
11-11 10:39:44.231: ERROR/AndroidRuntime(1683): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.database.CursorWindow.getString_native(Native Method)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.database.CursorWindow.getString(CursorWindow.java:361)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:49)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.database.CursorWrapper.getString(CursorWrapper.java:135)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at com.ravi.conproviderdemo1.ContentProviderDemo1Activity.readPhoneLookUp(ContentProviderDemo1Activity.java:63)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at com.ravi.conproviderdemo1.ContentProviderDemo1Activity$MyOnClickListener.onClick(ContentProviderDemo1Activity.java:74)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.view.View.performClick(View.java:2408)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.view.View$PerformClick.run(View.java:8816)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.os.Handler.handleCallback(Handler.java:587)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.os.Handler.dispatchMessage(Handler.java:92)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.os.Looper.loop(Looper.java:123)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at android.app.ActivityThread.main(ActivityThread.java:4633)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at java.lang.reflect.Method.invokeNative(Native Method)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at java.lang.reflect.Method.invoke(Method.java:521)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-11 10:39:44.231: ERROR/AndroidRuntime(1683):     at dalvik.system.NativeStart.main(Native Method)
11-11 10:39:44.231: WARN/ActivityManager(174):   Force finishing activity com.ravi.conproviderdemo1/.ContentProviderDemo1Activity
11-11 10:39:44.401: WARN/AudioFlinger(95): write blocked for 166 msecs, 384 delayed writes, thread 0xbb50
  

Ответ №1:

Попробуйте этот код

      Cursor c = activity.getContentResolver().query(Data.CONTENT_URI,
              new String[] {Data._ID, Data.DISPLAY_NAME,Phone.NUMBER,  
                            Data.CONTACT_ID,
                            Phone.TYPE, 
                            Phone.LABEL},
              Data.MIMETYPE   "='"   Phone.CONTENT_ITEM_TYPE   "'",
              null, 
              Data.DISPLAY_NAME);

    int count = c.getCount();
    boolean b = c.moveToFirst();
    String[] columnNames = c.getColumnNames();
    int displayNameColIndex = c.getColumnIndex("display_name");
    int idColIndex = c.getColumnIndex("_id");
    int col2Index = c.getColumnIndex(columnNames[2]);
    int col3Index = c.getColumnIndex(columnNames[3]);

    List<ContactItem> contactItemList = new LinkedList<ContactItem>();
    for(int i = 0; i < count ; i   ) {
        String displayName = c.getString(displayNameColIndex);
        String phoneNumber = c.getString(col2Index);
        int contactId = c.getInt(col3Index);
    }
  

Ответ №2:

Прочитайте основной номер телефона для пользователя (идентификатор пользователя в переменной ‘id’)

 Cursor cursor = mResolver.query(ContactsContract.Contacts.CONTENT_URI,
            new String[]{ContactsContract.Contacts.DISPLAY_NAME, 
                         ContactsContract.Contacts.HAS_PHONE_NUMBER,
                         ContactsContract.Contacts.PHOTO_ID
                         }, ContactsContract.Contacts._ID   "=?"
                         , new String[]{String.valueOf(id)}, null);

...
    if(cursor.moveToFirst()){
        if(cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) == 1){

            Cursor c = mResolver.query(ContactsContract.Data.CONTENT_URI
                    , new String[]{ Phone.NUMBER
                    }
                    , Phone.CONTACT_ID   "=? AND "   Data.MIMETYPE   "=? AND "   Data.IS_PRIMARY   "=1"
                    , new String[]{ String.valueOf(id),Phone.CONTENT_ITEM_TYPE }, null);
            if(c.moveToFirst()){
                // use phone number : sSecondLine.setText( c.getString(c.getColumnIndex(Phone.NUMBER)) );
            }
            c.close();
        }
cursor.close();
  

Наиболее важные строки импорта:

 import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Data;
  

Вот фрагмент для чтения всех телефонных номеров:

 Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI
                    , new String[]{ Phone.NUMBER, Phone.TYPE
                    }
                    , Phone.CONTACT_ID   "=? AND "   Data.MIMETYPE   "=?" 
                    , new String[]{      sValuesMap.get(name),Phone.CONTENT_ITEM_TYPE }, Data.IS_PRIMARY   " desc");
  

Первой записью будет основной номер телефона.

Ответ №3:

номер телефона, полученный из контактов на основе contact_id

 //Get phone number
           Cursor cursorPhone =   getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID   " = ? AND "  
                        ContactsContract.CommonDataKinds.Phone.TYPE   " = "  
                        ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,

                new String[]{id.toString()},
                null);
 String contactNumber = null;
 if (cursorPhone.moveToFirst()) {
            contactNumber =  cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            contactNumber = contactNumber.replaceAll("[\D]", "");
                System.out.println("contactnum"   contactNumber);
                if (contactNumber.length() >= 10) {
                    System.out.println("contactnum1"   contactNumber);
                    contactNumber = contactNumber.substring(contactNumber.length() - 10);
                    System.out.println("contactnum2"   contactNumber);
                }
                edittext.setText(contactNumber);
}