gpt4 book ai didi

android - 从 android 联系人中检索名字和姓氏导致 '1' 和 'null'

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:34 51 4
gpt4 key购买 nike

我正在使用以下代码从 android 联系人中检索名字和姓氏。DISPLAY_NAME 返回联系人的姓名,而名字和姓氏分别返回 1 和 null。以下是代码。

ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null);
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String firstname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
String lastname = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
System.out.println("firstname and lastname" + firstname+ " "+lastname);
phoneNo = phoneNo.replaceAll("\\D", "");
names.add(name);
phnno.add(phoneNo);
}
pCur.close();
}
}
}

当我将行 cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI 更改为 cr.query(ContactsContract.Data.CONTENT_URI 我得到的日志为

enter image description here

非常感谢您的建议。提前致谢

最佳答案

以下代码将帮助您获取名字和姓氏:

Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
Uri dataUri = Uri.withAppendedPath(contactUri, Contacts.Data.CONTENT_DIRECTORY);
Cursor nameCursor = getActivity().getContentResolver().query(
dataUri,
null,
Data.MIMETYPE+"=?",
new String[]{ StructuredName.CONTENT_ITEM_TYPE },
null);
while (nameCursor.moveToNext())
{

String firstName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA2));
String lastName = nameCursor.getString(nameCursor.getColumnIndex(Data.DATA3));

Toast.makeText(getApplicationContext(), "First name"+firstName, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Second name"+lastName, Toast.LENGTH_LONG).show();

return new String [] {firstName , lastName};
}

nameCursor.close();

关于android - 从 android 联系人中检索名字和姓氏导致 '1' 和 'null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13951609/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com