i am working on a wallpaper app in which i am saving a image with same name and sending it to gallery intent.
because of saving every image with same name i am having problem of getting same image every time in gallery intent.
what happening is new image is replacing but i am getting older image in gallery intent. new image replace older image but still gallery intent shows older image instead of new image
so i want to save image with new name every time but also delete older saved image.
Note: always save image as image++ but also delete previous image too.
my code:
public void setAsWallpaper(Bitmap bitmap) {
String dirname2 = "/Wallpaper/";
File myDir2 = new File(Environment.getExternalStorageDirectory()
.getPath() + dirname2);
myDir2.mkdirs();
String fname2 = "image" + ".jpg";
File file2 = new File(myDir2, fname2);
if (file2.exists())
file2.delete();
try {
FileOutputStream out = new FileOutputStream(file2);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
if (success) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_ATTACH_DATA);
intent.setDataAndType(Uri.parse("file://"
+ "/sdcard/Wallpaper/image.jpg"), "image/*");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
_context.startActivity(intent);
} else {
Toast.makeText(_context, "failed", Toast.LENGTH_SHORT).show();
}
}
If you don't have an original name for the image that you can send to your method as parameter. Then, the following method to generate random file name:
I usually loops throw all files in my folder and delete all images there(which is always one image). then save the new one with the random name as follow: