Ersin Gülbahar Ersin Gülbahar - 5 months ago 25
Android Question

How can I save my bitmap correctly for second time?

I want to save my bitmap to cache directory.
I use this code:

try {
File file_d = new File(dir+"screenshot.jpg");
@SuppressWarnings("unused")
boolean deleted = file_d.delete();
} catch (Exception e) {
// TODO: handle exception
}

imagePath = new File(dir+"screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}


it s working fine. But if I want to save different img to same path, something goes wrong. I mean it is saved to same path but I see it old image, but when I click the image I can see the correct image which I saved second time.

Maybe its come from cache but I do not want to see old image because when I want to share that image with whatsapp old image seen , if i send the image it seems correct.

I want to share saved image on whatsapp like this code:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imagePath));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);


How can I fix it?

thanks in advance.

Answer

Finally I solved my problem like this:

Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, getImageUri(context,bitmap_));
shareIntent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(shareIntent, getResources().getText(R.string.title_share)),whtsapp_result);

v

public Uri getImageUri(Context inContext, Bitmap inImage) {
          ByteArrayOutputStream bytes = new ByteArrayOutputStream();
          inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
          String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "TitleC1", null);
          return Uri.parse(path);
        }