I created a simple app to save a bitmap in internal storage and be able to show this bitmap in the android gallery like any other image.
The problem is: it isn't showing in the gallery after is saved... and I don't know what I am doing wrong. (I'm testing this on emulator)
Here is my class that handles the save of the Bitmap. This Saver class is used in my main activity when I click on a button saves the bitmap.
public class Saver {
private Context mContext;
private String mNameOfFolder = "Storager";
private String mNameOfFile = "Quote";
public void saveImage(Context context, Bitmap imageToSave) {
mContext = context;
// Create the directory
File dir = mContext.getDir(mNameOfFolder, Context.MODE_PRIVATE);
String filePath = dir.getAbsolutePath();
// Get the current date and time to attach to the name of the image
String currentDateAndTime = getCurrentDateAndTime();
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, mNameOfFile + currentDateAndTime + ".jpg");
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
galleryAddPic(file);
successSave();
} catch (FileNotFoundException e) {
Log.d("d", "file not found");
unableToSave();
} catch (IOException e) {
Log.d("d", "IO Exception");
unableToSave();
}
}
private void galleryAddPic(File file) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
private String getCurrentDateAndTime() {
Calendar calendar = Calendar.getInstance();
// Setting format of the time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
// Getting the formated date as a string
String formattedDate = dateFormat.format(calendar.getTime());
return formattedDate;
}
}
I even added the method galleryAddPic() that is provided by android developer site here to be able to add the image to Media Provider's database, making it available in the Android Gallery application and to other apps.
Third-party apps, including the MediaStore
, have no access to your app's internal storage. If you want third-party apps to have access to the file, use external storage.
Also, I have no idea why you are creating a ContextWrapper
here. If you have methods that require a Context
(e.g., getDir()
in your current code), call them on the Context
that is passed into your method.