在android中阅读联系人的问题

时间:2011-07-28 10:54:20

标签: java android android-emulator

我正在尝试使用此代码阅读联系人,但它只获取联系人而不是联系人数据。请 告诉我,我走错了路或者这有什么问题。

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();

这在我调试它时运行良好,它只打印ContactIds 1 2 3 4

但没有数据...(为长期问题道歉)

1 个答案:

答案 0 :(得分:1)

试试这段代码

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;