虽然位图似乎已正确获取,但变量“userBitmap”将保持为空。然而,当在我的平板电脑上向上或向下滚动时,新的列表行将包含图片,但它们都是相同的并且是错误的。真的,真的很困惑。我尝试了多种不同的方法从网络获取图像。任何帮助是极大的赞赏。
我的自定义适配器:
public class MessagesArrayAdapter extends ArrayAdapter<ChatData>
{
Bitmap userBitmap;
public MessageArrayAdapter(Context context, List<ChatData> objects)
{
super(context, 0, objects);
}
public View getView(int position, View convertView, ViewGroup parent)
{
ChatCell chatCell = new ChatCell();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.cell_chat, parent, false);
chatCell.usernameTextView = (TextView) convertView.findViewById(R.id.usernameTextView);
chatCell.messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
chatCell.userImageView = (ImageView) convertView.findViewById(R.id.userImageView);
ChatData chatData = getItem(position);
// Get user image from web
new loadImageAsync().execute(chatData.avatarURL);
chatCell.userImageView.setImageBitmap(userBitmap);
chatCell.usernameTextView.setText(chatData.username);
chatCell.messageTextView.setText(chatData.message);
return convertView;
}
private static class ChatCell
{
TextView usernameTextView;
TextView messageTextView;
ImageView userImageView;
}
private class loadImageAsync extends AsyncTask<String, Void, Double>{
@Override
protected Double doInBackground(String... params) {
userBitmap = loadImage(params[0]);
return null;
}
}
public Bitmap loadImage(String str) {
InputStream instream = null;
try {
HttpGet httpRequest = new HttpGet(URI.create(str));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
instream = bufHttpEntity.getContent();
Bitmap myBitmap = BitmapFactory.decodeStream(instream);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
//close input
if (instream != null) {
try {
instream.close();
} catch (IOException ioex) {
// Handle error
}
}
}
}
}
解决问题的最简单方法是使用一些库,例如Picasso。它不仅更易于使用并使代码更易于阅读,而且还可以防止图像太大时出现 OutOfMemory 异常。加载图像只需一行:
Picasso.with(context)
.load(urlOfYourImage)
.resize(50, 50) // here you resize your image to whatever width and height you like
.into(imageView)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)