I a creating an app in which i am displaying an imageview and two texviews in a recycler view. I am trying to set image resource of the imageview from urls by using an imageloader i created. ImageLoader class
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();
}
}
This is how i am calling in onBindViewHolder
new ImageLoader().loadImageFromURL(holder.newsIv,context.getString(R.string.images_folder_url) + newsCard.getImgurl());
The problem is if there are less images to load there is no problem but when the above line is called many time i am getting an OutOfMemory Error
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)
Is there something wrong with how use the threads. I am unable to understand this error and i am new to this.