0

I'm using Activity Result API to get multiple contents from gallery (since startActivityForResult() is deprecated).

MainActivity.java


LinearLayout ll;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = (Button) findViewById(R.id.btn);
    ll = (Button) findViewById(R.id.ll);
    
    btn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             launchImage.launch("image/*");
         }
    });
}

ActivityResultLauncher<String> launchImage= registerForActivityResult(
            new ActivityResultContracts.GetMultipleContents(),
            new ActivityResultCallback<List<Uri>>() {
                @Override
                public void onActivityResult(List<Uri> uri) {
                    try {
                        for (int i = 0; i < uri.size(); i++) {
                            ImageView imageView = new ImageView(MainActivity.this);
                            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(600,800);
                            lp.setMargins(0, 50, 0, 0);
                            imageView.setLayoutParams(lp);
                            imageView.setImageURI(uri.get(i));

                            ll.addView(imageView);
                        }
                    }
                    catch (NullPointerException e) {
                        e.printStackTrace();
                    }
               }
        });

The problem is when too many images are being added, my app crashes saying OutOfMemoryError. I believe the problem is with the file size of those images.
How do I reduce image size on this ActivityResult API?

Any help would be appreciated.
Thanks in advance.

Error from LogCat: java.lang.OutOfMemoryError: Failed to allocate a 38937612 byte allocation with 16772728 free bytes and 19MB until OOM

  • Hey did you try implementing the accepted answer here https://stackoverflow.com/questions/32244851/androidjava-lang-outofmemoryerror-failed-to-allocate-a-23970828-byte-allocatio – Varadharajan Raghavendran Feb 19 '22 at 12:38
  • Since the user will not be able to view all of those images at once, use a `RecyclerView`, coupled with an image-loading library (Glide, Picasso, etc.). Those image-loading libraries will also be able to help with downsampling the image to fit the size of the `ImageView`. – CommonsWare Feb 19 '22 at 13:18
  • Hey it worked...!!...Picasso library `.fit()` did the magic. I replaced the line `imageView.setImageURI(uri.get(i));` with `Picasso.with(MainActivity.this).load(uri.get(i)).fit().centerInside().into(imageView);` I tested it by adding about 50 images, and now my compiler executing them happily, no more crashing. Big thanks to both of you for your help. – steady blaze Feb 20 '22 at 09:50

0 Answers0