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?