1

When I try to save an image to an external directory, the directory is successfully scanned by MediaScannerConnection, but the images are not shown in gallery.

public void saveItem() {
        if (selectCount == 0) {
            Toast.makeText(getActivity(), "Select at least one image", Toast.LENGTH_SHORT).show();
        } else {
            Iterator iterator = selectedFile.iterator();
            while (iterator.hasNext()) {

                gridFilePath = new File(iterator.next().toString());
                String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myImages/";
                File destination = new File(destinationPath);
                try {
                    FileUtils.copyFileToDirectory(gridFilePath, destination);
                    MediaScannerConnection.scanFile(getActivity(), new String[]{destinationPath},
                            null, new MediaScannerConnection.MediaScannerConnectionClient() {
                                @Override
                                public void onMediaScannerConnected() {
                              
                                }

                                @Override
                                public void onScanCompleted(String path, Uri uri) {
                                    Log.d("Scan","Scanning Completed");
                                }
                            }

                    );
                     Log.d("Image Saved", "Saved");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           
            Toast.makeText(getActivity(), "Pictures Saved", Toast.LENGTH_LONG).show();
        }
    }
iCantC
  • 1,721
  • 1
  • 10
  • 23
Tushar Pingale
  • 237
  • 3
  • 18

1 Answers1

1

I fixed my problem adding the file's mimeType:

private void notifyNewFileToSystem(File file) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(file.getAbsolutePath());
    if (extension != null) {
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    }

    MediaScannerConnection.scanFile(getApplicationContext(),
            new String[]{file.getAbsolutePath()},
            new String[]{type},
            (path, uri) -> {
                Log.e(TAG, "Path: " + path);
                Log.e(TAG, "Uri: " + uri);
            }
    );
}

I found the solution to get the mimeType here: https://stackoverflow.com/a/8591230/2077248

Isquierdo
  • 651
  • 1
  • 8
  • 25