0

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.

Pavan Santhosh
  • 72
  • 1
  • 10
  • Does this answer your question? [Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM](https://stackoverflow.com/questions/32244851/androidjava-lang-outofmemoryerror-failed-to-allocate-a-23970828-byte-allocatio) – Franz Andel Jul 18 '20 at 12:31
  • No if i have lesser images to load there is no problem but if the number of images is more then it is giving the error – Pavan Santhosh Jul 18 '20 at 12:36
  • have you tried using glide library to load the image? https://github.com/bumptech/glide – Franz Andel Jul 18 '20 at 12:44
  • i do not want to use glide i wanted to implement my own – Pavan Santhosh Jul 19 '20 at 09:28

0 Answers0