阅读联系人时如何在android内容提供商中匹配DISPLAY NAME和Phone.NUMBER
Posted
技术标签:
【中文标题】阅读联系人时如何在android内容提供商中匹配DISPLAY NAME和Phone.NUMBER【英文标题】:How to match DISPLAY_NAME and Phone.NUMBER in android content provider wile reading contacts 【发布时间】:2013-06-26 11:34:46 【问题描述】:我一直在练习在 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();
请帮忙
【问题讨论】:
也许这可以帮助你***.com/questions/2356084/… 感谢 dazuku,这对我很有帮助。 【参考方案1】:这是一个简单的方法:
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();
不要忘记在清单中添加权限
【讨论】:
【参考方案2】:此代码基本上是先获取号码,然后使用它来搜索联系人姓名。
`
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;`
【讨论】:
以上是关于阅读联系人时如何在android内容提供商中匹配DISPLAY NAME和Phone.NUMBER的主要内容,如果未能解决你的问题,请参考以下文章