构建连接到蓝牙并检索与某个"姓名"匹配的联系人姓名/号码的设备,例如,如果我搜索"A - "并且我的手机中有以下联系人:
[0] "A - Dad "
[1] "A - Mom"
[2] "A - Grandmother"
[3] "FirendA "
它返回以下列表:
[0]
[0] A - Dad
[1] +33600000000
[1]
[0] A - Mom
[1] +33611111111
[2]
[0] A - Grandmother
[1] +33722222222
因此,此函数应返回一个数组,其中包含所有匹配联系人的数组中的联系人姓名和联系人号码(仅以 +336 或 +337(手机(开头(。但是到目前为止,我尝试的代码它返回了一个返回我空指针异常的代码:
public List<List<String>> getContacts(String name) {
List<List<String>> out = new ArrayList<>();
Cursor cursor = getContentResolver().query(
android.provider.ContactsContract.Contacts.CONTENT_URI,
new String[] { ContactsContract.Contacts.PHOTO_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID },
ContactsContract.Contacts.HAS_PHONE_NUMBER, null,
ContactsContract.Contacts.DISPLAY_NAME);
cursor.moveToFirst();
while (cursor.moveToNext()) {
String currentName = cursor.getString(1);
String currentId = cursor.getString(2);
Cursor cursor2 = getContentResolver()
.query(android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME },
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?",
new String[] { currentId }, null);
while (cursor2.moveToNext()) {
String currentNumber = cursor2.getString(0);
if(isMobilePhone(currentNumber)) {
List<String> tmp = new ArrayList<String>();
tmp.add(currentName);
tmp.add(currentNumber);
out.add(tmp);
break;
}
}
}
return out;
}
我像这样检索数组:
List<List<String>> contacts = myServiceBinder.getContacts(txt);
for(List<String> con : contacts) {
String[] array = new String[con.size()];
con.toArray(array); // fill the array
Log.wtf("test",array[0]+" : "+array[1]);
}
我做错了什么?
你的代码太复杂了。
- 正如您在投影中注意到的那样,您可以直接从
Phones
表中访问联系人 ID 和显示名称 - 可以直接迭代"电话"表,完全不需要查询"联系人"表
- 您可以使用
SQLITE
的LIKE
运算符在DISPLAY_NAME
字段中搜索关键字 - 您可以在列表中使用大小为 2 的
Array
,而不是大小为 2 的Pair
代码如下:
public List<Pair<String, String>> getContacts(String name) {
List<Pair<String, String>> results = new ArrayList<>();
String[] projection = new String[] { Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
String selection = Phone.DISPLAY_NAME + " LIKE '%" + name + "%'";
Cursor cur = getContentResolver().query(Phone.CONTENT_URI, projection, selection, null, Phone.DISPLAY_NAME);
while (cur.moveToNext()) {
long contactId = cur.getLong(0);
String name = cur.getString(1);
String phone = cur.getString(2);
Log.d("Contacts", "found: " + contactId + ", " + name + ", " + phone);
results.add(Pair.create(name, phone));
}
cur.close();
}