我正在创建一个应用程序,其中我在回收站视图中显示一个 imageview 和两个 texviews。我正在尝试使用我创建的图像加载器从 url 设置图像视图的图像资源。ImageLoader 类
public class ImageLoader {
private Bitmap bitmap;
public void loadImageFromURL(final ImageView imageView, final String url){
bitmap = null;
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream inputStream = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
imageView.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
catch (IOException e){
e.printStackTrace();
}
}
}).start();
}
}
这就是我调用 onBindViewHolder 的方式
new ImageLoader().loadImageFromURL(holder.newsIv,context.getString(R.string.images_folder_url) + newsCard.getImgurl());
问题是如果要加载的图像较少,则没有问题,但是当多次调用上述行时,我会收到 OutOfMemory 错误
java.lang.OutOfMemoryError: Failed to allocate a 9331212 byte allocation with 5141440 free bytes and 4MB until OOM
at dalvik.system.VMRuntime.newNonMovableArray(Native Method)
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
at android.graphics.BitmapFactory.decodeStreamInternal(BitmapFactory.java:650)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:626)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:664)
at com.example.news.ImageLoader$1.run(ImageLoader.java:24)
at java.lang.Thread.run(Thread.java:760)
如何使用线程有问题吗?我无法理解这个错误,我对此并不陌生。