我一直在练习阅读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();
请帮助
答案 0 :(得分: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();
不要忘记在清单中添加权限
答案 1 :(得分:1)
此代码基本上先获取Number,然后使用它来搜索联系人姓名。
`
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;`