1

我一直在练习在 android 中阅读联系人,我得到了联系人和号码,但它们排列得不好。我的意思是分配的名称不是号码的所有者。这是我的代码:

String [] projection= new String[]{ContactsContract.Contacts.DISPLAY_NAME,};
    String [] phoneProjection= new String [] {Phone.NUMBER};


     ContentResolver crInstance=getContentResolver();

    final  Cursor name=crInstance.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
    final Cursor phone=crInstance.query(Phone.CONTENT_URI, phoneProjection, null, null, null);
    contactview = (TextView) findViewById(R.id.contactview);
    name.moveToFirst();
    phone.moveToFirst();
    while (!name.isAfterLast()&&!phone.isAfterLast()){
        String pname=name.getString(name.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));



        contactview.append("Name:");
        contactview.append(pname);
        contactview.append("\n");


        final int contactNoColIndex= phone.getColumnIndex(Phone.NUMBER);

        String pnumber=phone.getString(contactNoColIndex);

        contactview.append("Phone:");
        contactview.append(pnumber);
        contactview.append("\n");
        contactview.append("\n");

        name.moveToNext();
        phone.moveToNext();
    }
    name.close();
    phone.close();

请帮忙

4

2 回答 2

3

这是一个简单的方法:

 ContentResolver resolver = getContentResolver();
 Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

    if (cursor.moveToFirst()) {

        String name;
        String phone;

        while (cursor.moveToNext()) {
            name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            // do what you want with the name and the phone number 

        }

    } else {
        Log.v(LOG_TAG, "Cursor is empty");
    }

cursor.close();

不要忘记在清单中添加权限

于 2016-02-24T10:31:57.047 回答
1

此代码基本上首先获取号码,然后使用它来搜索联系人姓名。

`

Cursor c;
c= mydb.query("sms", null, null, null, null, null, null);
while (c.moveToNext()) {
String name = null;
String sender=c.getString(c.getColumnIndex("phoneNo"));
String time=c.getString(c.getColumnIndex("smstype"));
String smsbody=c.getString(c.getColumnIndex("message"));
String[] projection = new String[]{
ContactsContract.PhoneLookup.DISPLAY_NAME};
Uri contacturi= Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(sender));
ContentResolver cr = getContentResolver();          
Cursor crc= cr.query(contacturi, projection, null, null, null);
if(crc.moveToNext()){   name=crc.getString(crc.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));  }   else{
name ="Unknown";
}
String senderid= name+" "+ sender;`
于 2014-02-20T13:38:00.903 回答