0

I want to use Glide to save a bitmap to a file and then share the picture with a nice Share button. I've used some code I've found in the docs, just like this:

Glide.with(getApplicationContext())
            .load(imageUrl)
            .asBitmap()
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap b, GlideAnimation<? super Bitmap> glideAnimation) {
                    File file = getExternalFilesDir(null);
                    try {
                        URI uri = new URI(imageUrl);
                        String path = uri.getPath();
                        String nameOfFile = file + "/" + path.substring(path.lastIndexOf('/') + 1);
                        OutputStream os = new FileOutputStream(nameOfFile);
                        b.compress(Bitmap.CompressFormat.JPEG, 100, os);
                        os.flush();
                        os.close();

                        Intent share = new Intent(Intent.ACTION_SEND);
                        share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + nameOfFile));
                        share.setType("image/*");
                        startActivity(Intent.createChooser(share, getResources().getString(R.string.action_share)));
                    } catch (IOException | URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
            });

The thing is that randomly, the app crashes because the Bitmap b is recycled before I compress it. How can I avoid this? Is there a better way?

Sam Judd
  • 7,317
  • 1
  • 38
  • 38
Matei Suica
  • 859
  • 1
  • 7
  • 17

1 Answers1

0

I have a similar issue with you. maybe you generate a bitmap use a same imageUrl in other place, then you invoke bitmap.recycled() manually. so you called asBitmap() may cause Bitmap recycled issue.

you can replace asBitmap() with asFile();

.asFile()
        .into(new SimpleTarget<File>()

or don't invoke bitmap.recycled()