我想在自定义ArrayAdapter中使用AsyncTask将图像从用户联系人加载到ImageView
这是我加载图片的代码段:
class LoadImage extends AsyncTask<String, Void, Bitmap>
{
protected Bitmap doInBackground(String... ac)
{
Bitmap contactPhoto = null;
try
{
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + ac[0] + "'", null, null);
if (cursor.moveToFirst())
{
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get the contact photo.
//
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactId));
InputStream input =
ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
contactPhoto = BitmapFactory.decodeStream(input);
}
cursor.close();
if(contactPhoto != null)
{
q.setImageBitmap(contactPhoto);
}
else
{
q.setImageResource(R.drawable.no_image);
}
}
catch (Exception e)
{
e.printStackTrace();
}
return contactPhoto;
}
@Override
protected void onPreExecute()
{
}
@Override
protected void onPostExecute(Bitmap contactPhoto)
{
}
}
在此代码中,图像加载在错误的位置,例如,为人3设置的人1的imgae!
如果我把这段代码放在onPostExecute方法中:
if(contactPhoto != null)
{
q.setImageBitmap(contactPhoto);
}
else
{
q.setImageResource(R.drawable.no_image);
}
无法加载任何内容。 我怎么解决这个问题?
答案 0 :(得分:1)
Hai我希望这会对你有帮助
class LoadImage extends AsyncTask<String, Void, List<Bitmap>>
{
protected List<Bitmap> doInBackground(String... ac)
{
List<Bitmap> totalBitmap = new ArrayList<Bitmap>();
Bitmap contactPhoto = null;
try
{
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + ac[0] + "'", null, null);
if (cursor.moveToFirst())
{
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get the contact photo.
//
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
Long.parseLong(contactId));
InputStream input =
ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
contactPhoto = BitmapFactory.decodeStream(input);
totalBitmap.add(contactPhoto);
}
cursor.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return totalBitmap;
}
@Override
protected void onPreExecute()
{
}
@Override
protected void onPostExecute(List<Bitmap> contactPhoto)
{
for (Bitmap bitmap : contactPhoto) {
if(contactPhoto != null)
{
q.setImageBitmap(bitmap);
}
else
{
q.setImageResource(R.drawable.no_image);
}
}
}
}