If we use the Android APIs to get the external storage directory, we get something like, /storage/emulated/0. If I run a recursive traversal on the same, I get a list of all the files and folders inside listed.
So, I thought of running the traversal on /storage thinking it would return all the public directories present. But, on running the same, I get a null list of Files inside it. For listing the files/folders, i have used the API: File.listFiles()
Why is this happening and how can I get a list of all publicly accessible files/folders on all the storages on Android?
I am using the below function for getting all the files of sdcard and its folder, subfolders. this works fine for me.
//A recursive function to list files of all folders and subfolders of SD Card
private void getAllFilesOfDir(File directory) {
Log.d("Spinner", "Directory: " + directory.getAbsolutePath() + "\n");
final File[] files = directory.listFiles();
if ( files != null ) {
for ( File file : files ) {
if ( file != null ) {
if ( file.isDirectory() ) { // it is a folder...
getAllFilesOfDir(file);
}
else { // it is a file...
Log.d("Spinner", "File: " + file.getAbsolutePath() + "\n");
allFileNameString.add(file.getName());
allFilePathString.add(file.getAbsolutePath());
}
}
}
}
}
Are you sure you gave correct path of sdcard storage directory, as the function call over here?
getAllFilesOfDir(Environment.getExternalStorageDirectory());
And try debugging inside the function, what goes wrong?
Related
I am currently working on an app, that goes through your phone and lists all available MP3 files. I managed to get this done and search for everything on the internal storage, but didnt manage to find a way using the envoirment to get to the sd card, when one is installed. This is my code - u will see a missing part when SD card is TRUE. Can you complete it?
public List<string> ReturnPlayableMp3(bool sdCard)
{
List<string> res = new List<string>();
string phyle;
if(sdCard)
{
// missing
}
else
{
try
{
var path1 = Android.OS.Environment.ExternalStorageDirectory.ToString();
var mp3Files = Directory.EnumerateFiles(path1, "*.mp3", SearchOption.AllDirectories);
foreach (string currentFile in mp3Files)
{
phyle = currentFile;
res.Add(phyle);
}
}
catch (Exception e9)
{
Toast.MakeText(ApplicationContext, "ut oh\n" + e9.Message, ToastLength.Long).Show();
}
}
return res;
}
}
It would need to return the exact same thing as it does for the internal storage only this time for the sd card. Right now, what is beeing returned is:
""/storage/emulated/0""
I hope you can help me. Thank you!
SO I found the place it is: /storage/05B6-2226/
But the digits refer to only MY sd card. How do I get this path programatically?
Take a look at these methods:
Context.GetExternalFilesDir
Returns the absolute path to the directory on the primary external
filesystem (that is somewhere on Environment.ExternalStorageDirectory)
where the application can place persistent files it owns. These files
are internal to the applications, and not typically visible to the
user as media.
Context.GetExternalFilesDirs
Returns absolute paths to application-specific directories on all
external storage devices where the application can place persistent
files it owns. These files are internal to the application, and not
typically visible to the user as media.
I've been searching for a couple of days with a lot of solutions that just ended up giving you the 'external' built in storage. Finally found this solution for the 'removable' SD Card and wanted to post it here in case someone else is still looking.
How to write on external storage sd card in mashmallow in xamarin.android
//Get the list of External Storage Volumes (E.g. SD Card)
Context context = Android.App.Application.Context;
var storageManager = (Android.OS.Storage.StorageManager)context.GetSystemService(Context.StorageService);
var volumeList = (Java.Lang.Object[])storageManager.Class.GetDeclaredMethod("getVolumeList").Invoke(storageManager);
List<Java.IO.File> ExtFolders = new List<Java.IO.File>();
//Select the Directories that are not Emulated
foreach (var storage in volumeList)
{
Java.IO.File info = (Java.IO.File)storage.Class.GetDeclaredMethod("getDirectory").Invoke(storage);
if ((bool)storage.Class.GetDeclaredMethod("isEmulated").Invoke(storage) == false && info.TotalSpace > 0)
{
//Get Directory Path
Console.WriteLine(info.Path);
}
}
Just wanna share my answer, where I have get the extStorages Path and I use this method in my simple file browser app.
public static string[] GetRemovableStorages()
{
List<string> extStorage = new List<string>();
//If this throws exception
string storageDir = (string)Environment.StorageDirectory;
//Try this
string storageDir = Directory.GetParent (Environment.ExternalStoragePublicDirectory).Parent.FullName;
string[] directories = Directory.GetDirectories(storageDir);
foreach(string dir in directories)
{
try
{
var extStoragePath = new Java.IO.File(dir);
bool isRemovable = Environment.InvokeIsExternalStorageRemovable(extStoragePath);
if(isRemovable) extStorage.Add(extStoragePath.AbsolutePath);
else return null;
}
catch
{
}
}
return extStorage.ToArray();
}
Elikill58's answer throws exception no such method "getDirectory" in my case but I recommend Elikill58's answer
I delete the file (camera file) like that:
public static void deleteFile(File file) {
if (file != null && file.exists()) {
if (!file.delete()) {
LogUtils.LOGE(TAG, "Delete file failed: " + file.getAbsolutePath());
} else {
LogUtils.LOGD(TAG, "Delete file successful: " + file.getAbsolutePath());
}
}
}
The delete indicates successful, but if I check on Gallery App on my phone, I can see this strange stuff:
It's on my Android 4.4.x. With my another mobile on Android 6.x there is no problem.
Could you help me guys?
As #CommonsWare said, since you are saving your file in the public storage, the gallery app will find the file and keep track, after you remove the gallery needs to update the references to now show the image anymore.
To avoid that you should always save your files in the private storage, you can find more info about storages here: https://developer.android.com/training/basics/data-storage/files.html
We've just fallen foul of the new permissions that apply to writing files to sd cards (external storage) on Android 4.4 (EACCES Permission Denied)
Prior to KitKat we set our writable folder like this:
mfolder = Environment.getExternalStorageDirectory().getPath() + "/appfiles";
However after hours of searching I've come to the conclusion, rightly or wrongly that on 4.4 devices to enable writing of files this needs to be changed to:
mfolder = Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.xyz.abc/appfiles";
So mfolder would be something like: /mnt/sdcard/Android/data/com.xyz.abc/appfiles
Is this correct, do we create a folder like the one above on the sdcard to enable 4.4 devices to write files?
mfolder is a String that we save to shared preferences.
Then we have this code that runs once if API>=19 that changes the mfolder String and then copies all the files from the old folder to the new 'kitkat' folder.
if (android.os.Build.VERSION.SDK_INT>=19){
if (!mfolder.contains("/Android/data/com.xyz.abc/appfiles")){
if (prefs.getBoolean("kitkatcheck", false)==false){
//update mfolder from
// /mnt/sdcard/appfiles
// to
// /mnt/sdcard/Android/data/com.xyz.abc/appfiles
String prekitkatfolder = mfolder;
String kitkatfolder = mfolder.replace("/appfiles", "/Android/data/com.xyz.abc/appfiles");
mfolder = kitkatfolder;
try {
File sd = new File(mfolder);
if(!sd.exists() || !sd.isDirectory()) {
sd.mkdirs();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Error creating Kitkat folder!\n" + e.toString(), Toast.LENGTH_LONG).show();
return;
}
prefEditor.putString("patternfolder", mfolder);
prefEditor.putBoolean("kitkatcheck", true);
prefEditor.commit();
//copy files and folder from old appfiles folder to new.
AllFiles.clear();
listFilesAndFilesSubDirectories(prekitkatfolder);
if (AllFiles.size()>0){
for (File child : AllFiles ) {
try {
File dest = new File(child.toString().replace(prekitkatfolder, kitkatfolder));
try {
String filePath = dest.getPath().substring(0, dest.getPath().lastIndexOf(File.separator));
File subfolder = new File(filePath);
if(!subfolder.exists() || !subfolder.isDirectory()) {
subfolder.mkdirs();
}
} catch (Exception ex) {
}
copyFile(child, dest);
} catch (Throwable t) {
}
}
}
}
}
I then notify the user that their files have been copied to the new folder and that due to the new permissions they would have to manually delete the old prekitkatfolder folder. I guess they will only be able to do this if they have a stock file manager or if they unmounted sd card and place it in a PC, due to the new 4.4 permissions?
Also, for us it appears that these 4.4 permissions are not affecting all our users with Kitkat. Some can still write to the original folder location on their external storage and some get the EACCES (Permission Denied) error. Can anyone throw any light on why this might be, one would think it would apply to all 4.4 devices using external storage?
As we have no actual 4.4 device we are having to test this code using the emulator (API 19) but we do not get the EACCES Permission Denied error. So we released a beta version with code above and have been told that the copied files ended up in internal storage, how can that be?
Any ideas what we're doing wrong, thanks in advance
Updated solution.
This sets and also creates the folder in the correct place for KitKat.
mfolder = this.getExternalFilesDir("asubfoldername").getAbsolutePath();
However, this isn't full-proof, if the Android device has both an internal and external secondary storage locations, the above will use the internal one. Not really what we want as we require path to removable sdcard or better still the path to the secondary storagelocation with the most free available space.
File[] possible_kitkat_mounts = getExternalFilesDirs(null);
Note the "s" on the end of getExternalFilesDirs. This creates an array of secondary external storage locations.
for (int x = 0; x < possible_kitkat_mounts.length; x++) {
//Log.d("test", "possible_kitkat_mounts " + possible_kitkat_mounts[x].toString());
boolean isgood=false;
if (possible_kitkat_mounts[x] != null){
isgood = test_mount(possible_kitkat_mounts[x].toString());
if (isgood==true){
arrMyMounts.add(newymounts(Device_get_device_info(possible_kitkat_mounts[x].toString()), possible_kitkat_mounts[x].toString()));
}
}
}
//sort arrMyMounts size so we can use largest
Collections.sort(arrMyMounts, new Comparator<mymounts>(){
public int compare(mymounts obj1, mymounts obj2){
return (obj1.avaliablesize > obj2.avaliablesize) ? -1: (obj1.avaliablesize > obj2.avaliablesize) ? 1:0 ;
}
});
if (arrMyMounts.size()>0){
mfolder = arrMyMounts.get(0).name + "/asubfoldername";
//Log.d("test", "selected kitkat mount " + kitkatfolder);
}else{
//do something else...
}
From the array of possible_kitkat_mounts we check via test_mount to see if we can actually write to the selected location and if successful we add that location to arrMyMounts.
By sorting arrMyMounts we can then get the location with the most available free space.
Hey presto, arrMyMounts.get(0).name is a kitkat secondary storage location with the most free space.
Google has blocked write access to external storage devices in Android 4.4. Until they change it there is no way to revert it back without root.
More info: https://groups.google.com/forum/#!msg/android-platform/14VUiIgwUjY/UsxMYwu02z0J
It might be working on some devices with Kitkat which have minisd card slot. It is confusing :(
Plzzz help me with this. Already late searching for the solution:
I want to list each and every Folder and file which is in the Android Phone's Internal Memory and External Memory.
The below code only gets list of files in one single directory.. But I'm unable to understand how would I list all the folders and files from internal and external memory.
..... List files = getListFiles(new File("YOUR ROOT")); ....
private List getListFiles(File parentDir) {
ArrayList inFiles = new ArrayList();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")){
inFiles.add(file);
}
}
}
return inFiles; }
Any help?
Look at the File object. It gives you methods to get all the files in a directory, tells you whether a file is a directory, and many other things.
You could easily do a recursive tree walk of the directory system. You probably will run into permissions issues, though, unless you have "rooted" your device.
I finally found this somewhere else.. This is how it's done (fully functional code)
public void walk(File root) {
File[] list = root.listFiles();
for (File f : list) {
if (f.isDirectory()) {
Log.d("realcrazy", "Dir: " + f.getAbsoluteFile());
walk(f);
}
else {
Log.d("realcrazy2", "File: " + f.getAbsoluteFile());
}
}
}
Most of the new android devices have an internal sdcard and an external sdcard. I want to make a file explorer app but I can't find out how to get the path to use in my app because
File file = Environment.getExternalStorageDirectory();
just returns in most device /mnt/sdcard
but there is another path for the other external sdcard like /storage1 or /storage2
. Any help appreciated.
How to get the internal and external sdcard path in android
Methods to store in Internal Storage:
File getDir (String name, int mode)
File getFilesDir ()
Above methods are present in Context class
Methods to store in phone's internal memory:
File getExternalStorageDirectory ()
File getExternalFilesDir (String type)
File getExternalStoragePublicDirectory (String type)
In the beginning, everyone used Environment.getExternalStorageDirectory() , which pointed to the root of phone's internal memory. As a result, root directory was filled with random content.
Later, these two methods were added:
In Context class they added getExternalFilesDir(), pointing to an app-specific directory on phone's internal memory. This directory and its contents will be deleted when the app is uninstalled.
Environment.getExternalStoragePublicDirectory() for centralized places to store well-known file types, like photos and movies. This directory and its contents will NOT be deleted when the app is uninstalled.
Methods to store in Removable Storage i.e. micro SD card
Before API level 19, there was no official way to store in SD card. But many could do it using unofficial APIs.
Officially, one method was introduced in Context class in API level 19 (Android version 4.4 - Kitkat).
File[] getExternalFilesDirs (String type)
It returns absolute paths to application-specific directories on all
shared/external storage devices where the application can place
persistent files it owns. These files are internal to the application,
and not typically visible to the user as media.
That means, it will return paths to both Micro SD card and Internal memory. Generally, second returned path would be storage path of micro SD card.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
Yes. Different manufacturer use different SDcard name like in Samsung Tab 3 its extsd, and other samsung devices use sdcard like this different manufacturer use different names.
I had the same requirement as you. so i have created a sample example for you from my project goto this link Android Directory chooser example which uses the androi-dirchooser library. This example detect the SDcard and list all the subfolders and it also detects if the device has morethan one SDcard.
Part of the code looks like this For full example goto the link Android Directory Chooser
/**
* Returns the path to internal storage ex:- /storage/emulated/0
*
* #return
*/
private String getInternalDirectoryPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
/**
* Returns the SDcard storage path for samsung ex:- /storage/extSdCard
*
* #return
*/
private String getSDcardDirectoryPath() {
return System.getenv("SECONDARY_STORAGE");
}
mSdcardLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String sdCardPath;
/***
* Null check because user may click on already selected buton before selecting the folder
* And mSelectedDir may contain some wrong path like when user confirm dialog and swith back again
*/
if (mSelectedDir != null && !mSelectedDir.getAbsolutePath().contains(System.getenv("SECONDARY_STORAGE"))) {
mCurrentInternalPath = mSelectedDir.getAbsolutePath();
} else {
mCurrentInternalPath = getInternalDirectoryPath();
}
if (mCurrentSDcardPath != null) {
sdCardPath = mCurrentSDcardPath;
} else {
sdCardPath = getSDcardDirectoryPath();
}
//When there is only one SDcard
if (sdCardPath != null) {
if (!sdCardPath.contains(":")) {
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File(sdCardPath);
changeDirectory(dir);
} else if (sdCardPath.contains(":")) {
//Multiple Sdcards show root folder and remove the Internal storage from that.
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File("/storage");
changeDirectory(dir);
}
} else {
//In some unknown scenario at least we can list the root folder
updateButtonColor(STORAGE_EXTERNAL);
File dir = new File("/storage");
changeDirectory(dir);
}
}
});
For all Android versions,
Permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
Use requestLegacyExternalStorage for Android 10 (add to AndroidManifest > application tag):
android:requestLegacyExternalStorage="true"
Get internal directory path:
#Nullable
public static String getInternalStorageDirectoryPath(Context context) {
String storageDirectoryPath;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
if(storageManager == null) {
storageDirectoryPath = null; //you can replace it with the Environment.getExternalStorageDirectory().getAbsolutePath()
} else {
storageDirectoryPath = storageManager.getPrimaryStorageVolume().getDirectory().getAbsolutePath();
}
} else {
storageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
}
return storageDirectoryPath;
}
Get external directories:
#NonNull
public static List<String> getExternalStorageDirectoryPaths(Context context) {
List<String> externalPaths = new ArrayList<>();
String internalStoragePath = getInternalStorageDirectoryPath(context);
File[] allExternalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
for(File filesDir : allExternalFilesDirs) {
if(filesDir != null) {
int nameSubPos = filesDir.getAbsolutePath().lastIndexOf("/Android/data");
if(nameSubPos > 0) {
String filesDirName = filesDir.getAbsolutePath().substring(0, nameSubPos);
if(!filesDirName.equals(internalStoragePath)) {
externalPaths.add(filesDirName);
}
}
}
}
return externalPaths;
}
Since there is no direct meathod to get the paths the solution may be
Scan the /system/etc/vold.fstab file and look for lines like this:
dev_mount sdcard /mnt/sdcard 1
/devices/platform/s3c-sdhci.0/mmc_host/mmc0
When one is found, split it into its elements and then pull out the
path to the that mount point and add it to the arraylist
emphasized textsome devices are missing the vold file entirely so we add a path here
to make sure the list always includes the path to the first sdcard,
whether real or emulated.
sVold.add("/mnt/sdcard");
try {
Scanner scanner = new Scanner(new File("/system/etc/vold.fstab"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (element.contains("usb"))
continue;
// don't add the default vold path
// it's already in the list.
if (!sVold.contains(element))
sVold.add(element);
}
}
} catch (Exception e) {
// swallow - don't care
e.printStackTrace();
}
}
Now that we have a cleaned list of mount paths, test each one to make
sure it's a valid and available path. If it is not, remove it from
the list.
private static void testAndCleanList()
{
for (int i = 0; i < sVold.size(); i++) {
String voldPath = sVold.get(i);
File path = new File(voldPath);
if (!path.exists() || !path.isDirectory() || !path.canWrite())
sVold.remove(i--);
}
}
I'm not sure how general an answer this but I tested it on a motorola XT830C with Android 4.4 and on a Nexus 7 android 6.0.1. and on a Samsung SM-T530NU Android 5.0.2.
I used System.getenv("SECONDARY_STORAGE") and Environment.getExternalStorageDirectory().getAbsolutePath().
The Nexus which has no second SD card, System.getenv returns null and Envirnoment.getExterna... gives /storage/emulated/0.
The motorola device which has an external SD card gives /storage/sdcard1 for System.getenv("SECONDARY_STORAGE") and Envirnoment.getExterna... gives /storage/emulated/0.
The samsumg returns /storage/extSdCard for the external SD.
In my case I am making a subdirectory on the external location and am using
appDirectory = (System.getenv("SECONDARY_STORAGE") == null)
? Environment.getExternalStorageDirectory().getAbsolutePath()
: System.getenv("SECONDARY_STORAGE");
to find the sdcard. Making a subdirectory in this directory is working.Of course I had to set permission in the manifest file to access the external memory.
I also have a Nook 8" color tablet. When I get a chance to test on them, I'll post if I have any problems with this approach.
but there is another path for the other external sdcard like /storage1 or /storage2
There is nothing in the Android SDK -- at least through Android 4.1 -- that gives you access to those paths. They may not be readable or writable by your app, anyway. The behavior of such storage locations, and what they are used for, is up to device manufacturers.
File main=new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()));
File[]t=main.getParentFile().listFiles();
for(File dir:t)
{
Log.e("Main",dir.getAbsolutePath());
}
Output:
E/Main: /storage/sdcard1
E/Main: /storage/sdcard0
I have one SD card and inbuilt memory.
There is no public api for get internal/external sdcard path.
But there is platform api called StorageManager in android.os.storage package. see http://goo.gl/QJj1eu .
There are some features such as list storage, mount/unmount storage, get mount state, get storage path, etc.
But it is hidden api and it should be deprecated or broken in next android release.
And some methods need special permission, and most are not Documented.
Try this code it will help
Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);