我想检索一个用户的配置文件和它的图像,但这不起作用。我总是得到一个空指针(
cursor.getCount() == 0
)有人能帮忙吗?
我的手机上有一个带有图像和电话号码的个人资料,但我看不到。权限(读写联系人权限)被授予,我可以检索所有电话联系人,但不能检索自己的配置文件。
有什么想法吗?
代码
void loadUser() {
Uri dataUri = Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY);
String[] selection = new String[]
{
ContactsContract.Data.RAW_CONTACT_ID,
ContactsContract.Data._ID,
ContactsContract.Profile.DISPLAY_NAME,
ContactsContract.Profile.PHOTO_URI,
ContactsContract.Profile.LOOKUP_KEY,
ContactsContract.Data.DATA_VERSION
};
Cursor cursor = MainApp.get().getContentResolver().query(
dataUri,
selection,
null,
null,
null);
if (cursor != null) {
L.d("MY PROFILE - cursor size: %d", cursor.getCount());
int rawId = cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
int id = cursor.getColumnIndex(ContactsContract.Data._ID);
int name = cursor.getColumnIndex(ContactsContract.Profile.DISPLAY_NAME);
int photoUri = cursor.getColumnIndex(ContactsContract.Profile.PHOTO_URI);
int lookupKey = cursor.getColumnIndex(ContactsContract.Profile.LOOKUP_KEY);
int version = cursor.getColumnIndex(ContactsContract.Data.DATA_VERSION);
try {
if (cursor.moveToFirst()) {
long phRawId = cursor.getLong(rawId);
int phId = cursor.getInt(id);
String phName = cursor.getString(name);
String phImageUri = cursor.getString(photoUri);
String phLookupKey = cursor.getString(lookupKey);
int phVersion = cursor.getInt(version);
boolean phExists = true;
L.d("MY PROFILE - RawID: %d, ID: %d", phRawId, phId);
// ... profile successfully retrieved
} else {
L.d("MY PROFILE - cursor is EMPTY");
}
} finally {
cursor.close();
}
} else {
L.d("MY PROFILE - cursor = NULL");
}
}
附加信息
我
认为
这个代码适用于我的安卓7的S6,但它在我的安卓8的新S9上不起作用(不能再在我的旧手机上测试它,因为它不再起作用了)。所以这个
可以
是Android版本特有的问题…