0

When you create a file in android, you have to call MediaScannerConnection.scanFile() on it, so that it gets displayed in the file explorer.

However, when I try to do this with a directory it gets treated as a file.

File dir = new File("folder/subfolder/folder2");
dir.mkdirs();
MediaScannerConnection.scanFile(_context, new String[]{dir.getAbsolutePath()}, null, null);

"folder2" should be a directory not a file. How can I fix this?

"folder2" should be a directory not a file

miXo
  • 193
  • 11
  • @CommonsWare: But then it wont be visible in file explorer. – miXo Sep 17 '15 at 18:58
  • 'When you create a file in android, you have to call MediaScannerConnection.scanFile() on it, so that it gets displayed in the file explorer.'. No. That is not true. A normal file explorer does not depend on the MediaStore. It will just show the folder. About which file explorer are you talking? – greenapps Sep 17 '15 at 20:39
  • @greenapps: Android File Transfer app. But it looks like there it's not the problem in the exploerer ("All phones using MTP instead of USB Mass storage do not properly show the list of files when that phone is connected to a computer using a USB cable."): http://stackoverflow.com/questions/13737261/nexus-4-not-showing-files-via-mtp – miXo Sep 17 '15 at 22:12
  • You are talking about a file explorer on your PC. You should have said so to begin with. Indeed then MTP can be in use and the MediaStore is involved. Next time be clear please. – greenapps Sep 18 '15 at 05:51

1 Answers1

0

A workaround that worked for me:

  • create a file in that directory
  • scan the file
  • delete the file again
  • finally scan the file again (because it would still be displayed otherwise)

public static void scanEmptyFolder(final Context context, File targetFile){
    final File dummy = new File(targetFile, "init");
    try {
        dummy.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    MediaScannerConnection.scanFile(context, new String[]{dummy.getAbsolutePath()}, null, new MediaScannerConnection.OnScanCompletedListener() {
        @Override
        public void onScanCompleted(String s, Uri uri) {
            // delete file and scan again (because file should not be displayed)
            dummy.delete();
            MediaScannerConnection.scanFile(context, new String[]{dummy.getAbsolutePath()}, null, null);
        }
    });
}
Lars
  • 2,315
  • 2
  • 24
  • 29