如何获取所有联系人全名和电话号码,仅当他们有电话号码?
我想让所有有电话号码的联系人,并记录他们的全名和电话号码(以及将来他们的联系照片),但我被卡住了。这里是我的代码:如何获取所有联系人全名和电话号码,仅当他们有电话号码?
String contacts = "";
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone == "1") {
contacts += cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ":" + "how to get number?" + "|";
}
}
cursor.close();
字符串hasPhone应该包含“1”,如果联系人有一个电话号码,然后添加名相关人员的电话号码,以“接触”的字符串。即使hasPhone包含“1”(从logcat中检查),条件语句中的任何代码都不会运行。另外,您如何获得电话号码,ContactsContract.Contacts中没有任何内容。
试试这个:
if (Integer.parseInt(hasPhone) > 0) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+ contactId, null, null);
phones.moveToNext(); //if you are interested in all contact phones do a while()
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phones.close();
contacts += cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) + ":" + phoneNumber + "|";
}
使用此代码后:http://pastebin.com/hrtFayqx我仍然没有在Logcat中,没有错误,没有什么,可悲的。我不明白为什么。我也有READ_CONTACTS权限。我也确信这个代码正在被处理。 – Qasim 2012-01-13 00:21:16
@Qasim:试试最后一个,适合我! – 2012-01-13 00:49:32
更改为:为对象平等
hasPhone.equals("1")
==操作符检查,也就是说,如果hasPhone是相同的对象为“1”,这显然是错误的。
你想检查Lexicographic是否相等,所以你应该使用String的equals方法,它比较两个对象字符串的等式,意思是检查两个字符的顺序是否相同。
此外,考虑使用LookupKey,如下所述:http://developer.android.com/resources/articles/contacts.html
如果你想保存特定联系人将来参考。
即使那样,我仍然没有得到任何东西。它真的很奇怪。 – Qasim 2012-01-13 00:22:39
看到它一次可它是你 检查http://stackoverflow.com/questions/12026173/android-cant-get-phone-number-有用一些联系人/ 12747910#12747910 – Jeetu 2012-10-05 14:07:17