Aziz Erel
Aziz Erel

Reputation: 23

How to show saved photo in gallery in Android app

I save picture and see in file manager but I don't see in my gallery? How to fix?

I think my error in Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFolder";

String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFolder";
File dir = new File(file_path);

if(!dir.exists())
{
    dir.mkdirs();
}

String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()).concat(".png");
File file = new File(dir, name);

FileOutputStream fOut;
try {
    fOut = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
    fOut.flush();
    fOut.close();

    return Uri.fromFile(file);
} catch (Exception e) {
    e.printStackTrace();
}

return null;

Upvotes: 0

Views: 40

Answers (2)

Tyler V
Tyler V

Reputation: 10910

You have to add it to the MediaStore to make it show up in the gallery. The following code works for me (put it after your existing code where you've written the file) to add the file manually with your own custom description etc...

I saved it here:

String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
String path = dir + "/" + filename;

using pretty similar code to what you have, then add it to MediaStore with:

long size = new File(path).length();
long currentTime = System.currentTimeMillis();

ContentValues values = new ContentValues(8);
String mimeType = "image/png";
String fileDescription = "My description";

// store the details
values.put(MediaStore.Images.Media.TITLE, name);
values.put(MediaStore.Images.Media.DISPLAY_NAME, name);
values.put(MediaStore.Images.Media.DATE_ADDED, currentTime);
values.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
values.put(MediaStore.Images.Media.DESCRIPTION, fileDescription);
values.put(MediaStore.Images.Media.ORIENTATION, 0);
values.put(MediaStore.Images.Media.DATA, path);
values.put(MediaStore.Images.Media.SIZE, size);

try {
    context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
catch(Exception e) {
    e.printStackTrace();
}

Upvotes: 1

Pawel
Pawel

Reputation: 17258

A lot of gallery apps rely on cached media columns and data in MediaStore instead of actually reading and parsing directories. Some of them will trigger automatic rescan, but not all of them.

Use MediaScannerConnection to update MediaStore with your file:

MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null, null);

Upvotes: 0

Related Questions