key*_*bee 4 android photo image contacts
我让用户在我的应用程序中选择一个联系人,然后将其显示在主屏幕小部件上,但是照片没有显示,我不知道出了什么问题.
这就是我获取照片的参考方式:
...
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
String name = c.getString(2);
int photo = c.getInt(3);
showSelectedNumber(type, number, name, photo);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我显示它的方式:
public void showSelectedNumber(int type, String number, String name, int photo) {
mAppWidgetPrefix.setText(name);
pickedNumber.setText(number);
pickedPhoto.setImageResource(photo);
}
Run Code Online (Sandbox Code Playgroud)
为什么不起作用?
Vit*_*ski 11
您正尝试将ContactsContract.Data表中的行ID设置为您的资源ID ImageView.当然它不会起作用.它甚至没有任何意义.
您应该首先从数据库中检索原始照片,然后才能显示它.
例如,您可以使用此代码在指向图像数据的行ID的帮助下检索图像位图(我已经重新创建了一些代码来测试它):
private void queryContactInfo(int rawContactId) {
Cursor c = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
}, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[] { Integer.toString(rawContactId) }, null);
if (c != null) {
if (c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
String name = c.getString(2);
int photoId = c.getInt(3);
Bitmap bitmap = queryContactImage(photoId);
showSelectedNumber(type, number, name, bitmap);
}
c.close();
}
}
private Bitmap queryContactImage(int imageDataRow) {
Cursor c = getContentResolver().query(ContactsContract.Data.CONTENT_URI, new String[] {
ContactsContract.CommonDataKinds.Photo.PHOTO
}, ContactsContract.Data._ID + "=?", new String[] {
Integer.toString(imageDataRow)
}, null);
byte[] imageBytes = null;
if (c != null) {
if (c.moveToFirst()) {
imageBytes = c.getBlob(0);
}
c.close();
}
if (imageBytes != null) {
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
} else {
return null;
}
}
public void showSelectedNumber(int type, String number, String name, Bitmap bitmap) {
mInfoView.setText(type + " " + number + " " + name);
mImageView.setImageBitmap(bitmap); // null-safe
}
Run Code Online (Sandbox Code Playgroud)
您还可以将http://developer.android.com/reference/android/provider/ContactsContract.Contacts.Photo.html 视为获取联系人照片的便捷提供者目录.还有一个例子.
| 归档时间: |
|
| 查看次数: |
5635 次 |
| 最近记录: |