Folder added on Android is not visible via USB - android

I'm trying to save pictures in a subfolder on Android. Here's a bit of my code:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
path = new File(path, "SubDirName");
path.mkdirs();
(I've tried getExternalStorageDirectory instead of getExternalStoragePublicDirectory and the Pictures folder instead of DCIM.)
Any subfolder I add, including its contents, don't show up in Windows Explorer when the device is connected via USB. It does show in the Android File Manager, though.
I've tried broadcasting the ACTION_MEDIA_MOUNTED intent on the new directory's parent. It didn't work.
If I add a file in Windows, it shows up on Android. If I add a file on Android via the File Manager, it shows up in Windows. If I add the file programmatically, it shows up on the Android File Manager, but not in Windows Explorer. And I need to get it from Windows, and I don't want the final user to have to create the folder manually.
What am I doing wrong?

I faced the same issue and rebooting either the Android device or the PC is not a practical solution for users. :)
This issue is through the use of the MTP protocol (I hate this protocol). You have to
initiate a rescan of the available files, and you can do this using the MediaScannerConnection class:
// Snippet taken from question
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
path = new File(path, "SubDirName");
path.mkdirs();
// Initiate a media scan and put the new things into the path array to
// make the scanner aware of the location and the files you want to see
MediaScannerConnection.scanFile(this, new String[] {path.toString()}, null, null);

The way used in Baschi's answer doesn't always work for me. Well, here is a full solution.
// Snippet taken from question
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
path = new File(path, "SubDirName");
path.mkdirs();
// Fix
path.setExecutable(true);
path.setReadable(true);
path.setWritable(true);
// Initiate media scan and put the new things into the path array to
// make the scanner aware of the location and the files you want to see
MediaScannerConnection.scanFile(this, new String[] {path.toString()}, null, null);

The only thing that worked for me was this:
Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri fileContentUri = Uri.fromFile(path);
mediaScannerIntent.setData(fileContentUri);
this.sendBroadcast(mediaScannerIntent);
Credit to https://stackoverflow.com/a/12821924/1964666

None of the above helped me, but this worked:
The trick being to NOT scan the new folder, but rather create a file in the new folder and then scan the file. Now Windows Explorer sees the new folder as a true folder.
private static void fixUsbVisibleFolder(Context context, File folder) {
if (!folder.exists()) {
folder.mkdir();
try {
File file = new File(folder, "service.tmp");//workaround for folder to be visible via USB
file.createNewFile();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
null, (path, uri) -> {
file.delete();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()} ,
null, null);
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks to https://issuetracker.google.com/issues/37071807#comment90
You also should scan every created file in the directory analogically:
private static void fixUsbVisibleFile(Context context, File file) {
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
null, null);
}

If you add the folder to the SD card from the PC directly to the card through the card reader, it will not show in Windows Explorer when connected with the phone.
The solution is to copy or move the same folder using the Android file manager program and then it will be listed in the SD card index when connected to the PC.

It's work fine for me.
MediaScannerConnection.scanFile work if there is file in directory (not directory)
private fun checkMTPFolder(f: File, context: Context) {
if (f.isDirectory) {
val newFilePath = f.absolutePath + "/tempFIle"
val newFile = File(newFilePath)
newFile.mkdir()
MediaScannerConnection.scanFile(context, arrayOf(newFilePath), null, object : MediaScannerConnection.OnScanCompletedListener {
override fun onScanCompleted(p0: String?, p1: Uri?) {
val removedFile = File(p0)
removedFile.delete()
MediaScannerConnection.scanFile(context,arrayOf(removedFile.absolutePath), null, null)
}
})
}
}

I have solved this problem by toggling the phone setting:
After a directory is created and/or a file saved, change from (MTP) mode to USB (SD card) mode for a moment, wait for the SD card mounting on the PC, so the directory and file will be shown.
Turn back to (MTP) mode again where the last file still shows up.
When re-saving a file, you have to change to USB again to see it.

Just create the directory on the PC first, and then copy it over to the SD card/phone storage.
You can either put in the contents into the folder first and copy over or just the folder first. As long as the folder is created from the PC, any content can just be copied directly to internal/external mobile devices. For zipped content, it cannot be directly unzipped and copied over unfortunately; you need to unzip them first.

Related

Qt, MediaScannerConnection does not work on creating folder second time

To make visible to my folder from Windows with USB connection (MTP) : /storage/emulated/0/MyFolder
I put a dummy file on this folder and use MediaScannerConnection.scanFile to scan this file.
File file = new File(Environment.getExternalStorageDirectory() + "MyFolder" + File.separator + "dummy.txt");
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null, null);
All work well at the first time, i see that folder and dymmy file on windows. But if i delete the whole folder, when folder are re-created, it is seen as a file of 4K on windows.
Is there any cache on this level ? And how can i refresh this cache ?
Thank you
This bug of MTP still persists :
https://issuetracker.google.com/issues/36956498
https://issuetracker.google.com/issues/37071807
MediaScannerConnection.scanFile is not a perfect solution.

How could I create a file in the "Internal Storage" Directory?

I have a Samsung Galaxy S6. I'm currently working on a test application where I would like quick access to a folder with my files.
Using the provided "My Files" Application, it specifies that all those folders are in the "Internal Storage" folder.
I know that internal storage is private, but I want to create a folder in the default folder that windows accesses when the phone is plugged in.
For example, the following code does not create the directory in the correct location.
File storage = new File("/testappplication");
if(!storage.exists()) {
storage.mkdir();
System.out.println("Folder Created");
}
I just want to know the path where to create the folder. Many other applications have storage here, so I know its possible.
You can't create a directory inside the internal storage of the device. Except you've a root access for the app.
So, the following code won't work:
File storage = new File("/testappplication");
Because it tell the app to create a testappplication in the root folder.
You can only create the directory inside your app private folder within the following path:
String path = getFilesDir().getAbsolutePath();
And make the folder using the path.
Or you can use something like this:
File folder = new File(context.getFilesDir(), "testappplication");
if (!folder.exists()) {
folder.mkdirs();
} else {
// folder is exist.
}
Read more at Saving Files
First just for trial make runtime permmision and then try the following code
private void createInternalFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+"/"+getApplicationContext()
.getPackageName()+"/File/profile");
if (!mediaStorageDir.exists()) {
mediaStorageDir.mkdirs();
} }
then check your internal storage in which you will find a folder whose name is your package name
After a while later I found the answer to this question.
public void createDirectory() {
File file = new File(Environment.getExternalStorageDirectory(), "/test");
if (!file.exists()) {
file.mkdirs();
Log.w("DEBUG", "Created default directory.");
}
}
This is how you create it code wise. The reason it wasn't creating was due to Samsungs weird permissions.
Make sure you have the storage permission enabled in Settings -> Apps -> App Name -> Permissions. I needed to turn it on so it would create the folder.

Android app generate

I'm having a little problem with my android app.
My app generates a .html file when a "export button" is pressed.
But I can't see the file in my pc or in the Android's Download app. I can only see it in Astro file manager.
That's how I generate and saved my file .
String string = "Hello World"
String filename = "/sdcard/Download/teste.html";
FileOutputStream outputStream;
try {
File file = new File(filename);
boolean newFile = file.createNewFile();
if(!newFile){ //if the file exists I delete it and generate a new file
file.delete();
newFile=file.createNewFile();
}
Context context=getActivity();
FileOutputStream fOut = new FileOutputStream(file,true);
// Write the string to the file
fOut.write(string.getBytes());
/* ensure that everything is
* really written out and close */
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}
I suppose there is a way to visualize this file without the Astro app but I can't find how do this, if someone can help I'll be grateful.
Thanks
First, never hardcode paths. Your path will be wrong on some Android devices. Please use the proper methods on Environment (e.g., getExternalStoragePublicDirectory()) or Context (e.g., getExternalFilesDir()) to get the roots under which you can safely place files.
Beyond that, files that you write to external storage will not be visible to PCs until that file is indexed by MediaScannerConnection, and even then it might require the user to perform some sort of "reload" or "refresh" operation in their file browser to see it.
I have another blog post with more about external storage which may be of use to you.

File creation in SD card not working

I am trying to create a file and store it in SD Card to be used as an input for some processing for an apps.
After searching for a while, I got this code which can create a file in SD card.But after running this,I couldn't see any file created in my SD card. Can anyone please help me what I am missing here.
BufferedWriter out = new BufferedWriter(new FileWriter(FileDescriptor.err));
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()) {
File perffile = new File(root, "samplefile.txt");
FileWriter perfwriter = new FileWriter(perffile, true);
out = new BufferedWriter(perfwriter);
}
} catch (IOException e) {
Log.e(TAG, "-Could not write file " + e.getMessage());
return;
}
If you want to add a file or folder or move application into your SD Card just do the following:
steps:
1) Open your Android application's source code file with a text or programming editor.
2) Browse to the location in the source code where you wish to call the function that writes a file to the device's external storage.
3) Insert this single line of code to check for the SD card:
File sdCard = Environment.getExternalStorageDirectory();
4) Insert these lines of code to set the directory and file name:
File dir = new File (sdcard.getAbsolutePath() + "/folder1/folder2");
dir.mkdirs();
File file = new File(dir, "example_file");
// The mkdirs funtion will create the directory folder for you, use it only you want to create a new one.
5) Replace "/folder1/folder2" in the above code with the actual path where you intend to save the file. This should be a location in which you normally save your application files. Also, change the "example_file" value to the actual file name you wish to use.
6) Insert the following line of code to output the file to the SD card:
FileOutputStream f = new FileOutputStream(file);
Finally step 7:
Save the file, then compile it and test the application using the Android emulator software or the device.
This will works!!! ;-)

Create a folder and write into it in the root of android

I'm not trying to write into the external sd at /mnt/sdcard. I'm trying to create a folder for may app files and have them accesible by others.
I have an app called Libra that generates .csv files when exporting data and all af it goes to /Libra/ folder. I want my app to do the same.
As far as I've seen there's external storage which is the sd and internal which is a non public place for the app.
How can I make a dir at the root of the android file system as Libra does ?
If I ask for the external storage I get the following non desired locations :
Environment.getExternalStorageDirectory()
/storage/emulated/0/ (in my Nexus)
/mnt/sdcard (in the emulator)
If I try to make the folder in an absolute path /MyDiary It returns Error creating folder
File folder = new File("/MyDiary");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(getBaseContext(), "Already exists", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Error creating directory", Toast.LENGTH_LONG).show();
return;
}
If I try to check if the Libra folder does exists, it says it doesn't exist:
File folder = new File("/Libra");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
if (success) {
Toast.makeText(getBaseContext(), "Libra exists", Toast.LENGTH_LONG).show();
}
Note: I've got the manifest permissions to write in external storage.
The root is a ramdisk. And the folder in it some are created by init.rc. Only init.rc have permission to create the folder in the ramdisk.
If you create the folder by init.rc, you still need init.rc help to mount a true stroage device on the new folder.
Repack like The init.rc file regenerated on restart
First of all you need root access Permissions to write.
You can see whether it has created folder there or not using rootexplorer app.
Try this after getting root access.
I don't think that's the right way to create a File in the Android OS.
From http://developer.android.com/training/basics/data-storage/files.html:
If you want to save public files on the external storage [I've read your advice, but I think this way you can access files from multiple apps, if that's what you want], use the getExternalStoragePublicDirectory() method to get a File representing the appropriate directory on the external storage. The method takes an argument specifying the type of file you want to save so that they can be logically organized with other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES. For example:
public File getAlbumStorageDir(String albumName) {
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
try first getting superuser permission to your app.Run linux commands for making folder and files into which you want to write data(You can do this with only linux commands)just at 1st run of your app.Then you can write data to files by getting FileOutputStream("filename") object.Leave ur remarks if it worked or not.
partial code for above procedures is
Process p=Runtime.getRuntime().exec("su");
OutputStream o=p.getOutputStream();
o.write("mkdir foldername\n".getBytes());
o.write("cd foldername\n".getBytes());
o.write("cat > filename\n".getBytes());
o.write("exit\n".getBytes());
o.flush();
p.waitFor();

Categories

Resources