简体   繁体   English

在Android中阅读联系人的问题

[英]problem with reading contacts in android

i'm trying to read contacts with this code but it only gets Contacts but not contacts data.Please tell me am i going on a wrong path or what is wrong with this. 我正在尝试使用此代码读取联系人,但它只会获取联系人,而不会获取联系人数据。请告诉我我走的路错误还是这有什么问题。

Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    while(contacts.moveToNext()) {
       int contactIdColumnIndex = contacts.getColumnIndex(ContactsContract.Contacts._ID);
       long contactId = contacts.getLong(contactIdColumnIndex);
       System.out.println(contactId);

       Cursor c = getContentResolver().query(Data.CONTENT_URI,
                  new String[] {Data._ID, Phone.NUMBER, Phone.TYPE},
                  Data.CONTACT_ID + "=?" + " AND "
                          + Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'",
                  new String[] {String.valueOf(contactId)}, null);
//retrieving data
 while(c.moveToNext()){
           long Id=c.getLong(0);
           String number=c.getString(1);
           String type=c.getString(2);
           String name=c.getString(3);
           System.out.println(Id);
           System.out.println(number);
           System.out.println(type);
           System.out.println(name);

       }

       c.close();
}
contacts.close();

This runs well when i debug this and it only print ContactIds only 1 2 3 4 当我调试它时,它运行良好,并且只打印ContactIds 1 2 3 4

but no data...(apologize for long question) 但没有数据...(很长的问题表示歉意)

try this code 试试这个代码

String number = "";

    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                            new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, 
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                            new String[]{id}, null);

                    while (pCur.moveToNext()) {
                        for(int i=0;i<pCur.getColumnCount();i++)
                            number = pCur.getString(i);

                    } 
                    pCur.close();
                    pCur = null;
                }

        }
    }
    cur.close();
    cur = null;
    cr = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM