Unable to save data in SD Card Directory - android

I have write a code to find if SD card path if available which is like this
File[] paths = ContextCompat.getExternalFilesDirs(context, null);
if (paths.length > 1) {
if (paths[1] != null) {
root = paths[1].getAbsolutePath();
// for sd card
} else {
root = Environment.getExternalStorageDirectory().toString();
}
} else {
root = paths[0].getAbsolutePath();
}
I am saving my data in path "/storage/4130-1912/Android/data/com.enable/files" but I wanted to save data outside Android folder.
I have also tried to make an directory outside the Android folder.But unable to make it.I am testing in Lave phone with version Marhmallow

As you are using Marshmallow, you should be requesting runtime permissions (more details here). Despite that, you may add the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for external storage access. You can find more information on how to here.
You can access the external storage path like this: Environment.getExternalStorageDirectory().getAbsoluteFile(). If you are getting FileNotFoundException, it's probably because you didn't add an additional "/" before your file. Example:
File file = new File(Environment.getExternalStorageDirectory().getAbsoluteFile() +
"/your_file.txt");

I am saving my data in path "/storage/4130-1912/Android/data/com.enable/files"
Ok. Go ahead. You will succeed.
but I wanted to save data outside Android folder.
Well that is not possible anymore on modern Android systems.
Even inside the Android folder you can only write to mentioned private directory for your app.
If you want to write to the whole micro SD card then use the storage access framework.

This will help you
As miguelarc said:
As you are using Marshmallow, you should be requesting runtime
permissions (more details here). Despite that, you may add the
WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE for external
storage access.
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + getPackageName() + "/yourdir");
if (f.mkdirs() || f.isDirectory())
Log.e("path",f.getPath());
//do what you want
}

Related

How to write files on SD Card from Android API 24+

I have a big problem. I want to save some files that I download from internet with my application, into my SD card fallowing this path:
/storage/9016-4EF8/Android/data/com.my.application/files
But I don't want to hardcode this string inside my code. So how can I do it programmatically?
I have already ask permission to write on external storage.
Currently inside my code there is this piece of code below:
File sdcard = new File(context.getExternalFilesDir(null).getAbsolutePath() + "/Video scaricati/");
But with it, my application saves the files inside:
/storage/emulated/0/Android/data/com.my.application/files/Video scaricati
that it isn't in my SD card.
How can I do it?
Take the second item returned by
File dirs[] =getExternalFilesDirs();
Check if the array contains more then one element before use. Not everybody puts a micro SD card in.
Try changing to Environment.getExternalStorageDirectory() like this
new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Video scaricati/");

Get path for data storage

I need to create file in storage card from my Android program. I know I can create this file only in particular location like \Card\Android\data\my.application.package\. How to get this directory exact location? Code below brings path /data/my.application.package/Log and mkdirs() does not creates directories.
String path = "Log";
File root = new File(Environment.getDataDirectory().getAbsolutePath(),
"my.application.package" + File.separator + path);
boolean dirExists = true;
if (!root.exists()) {
dirExists = root.mkdirs();
}
How to get the same application path on internal storage?
You should use getFilesDir() for getting app specific internal File path and getExternalFilesDir() for getting app specific external File path.
Note that on Android 4.3 (API level 18) or lower, your app need to request storage-related permissions to access app-specific directories within external storage.
For more information see https://developer.android.com/training/data-storage/app-specific

Android write file on External SD Card for android 5+

I am unable to write file to external SD Card . I get error message EAcess denied. I have searched a lot on internet and found that from Android 4.4 + android's Storage Access Framwork (SAF) is required to write file.
But I am using some android applications which are able to write(Create/Delete/Rename) file on SD Cards. They are not using SAF.
So please help me as to how can I do this without using SAF framwork.
Thanks
There are a lot of confusions talking about External Memory of Android. It doesn't point to Removable SD MICRO CARD actually. So, what Google thinks "external memory" means
Refer to Android API Document
Every Android-compatible device supports a shared "external storage"
that you can use to save files. This can be a removable storage media
(such as an SD card) or an internal (non-removable) storage. Files
saved to the external storage are world-readable and can be modified
by the user when they enable USB mass storage to transfer files on a
computer.
The fact is Environment.getExternalStorageDirectory() and Context.getExternalFilesDirs() could return an emulated External Memory located inside the Internal storage. Thus, these functions themselves don't give an expected results. The SECONDARY_STORAGE environment variable can help to get a real path of removable memory but writing on root of this isn't allowed because of OEM implementation. In this case, we should try to get app's data folder by Context.getExternalFilesDirs() or ContextCompat.getExternalFilesDirs() on which app's data file is allowed to be read and written.
I solve my problem by using below method, please check it and hope it helps you overcome your issues.
#TargetApi(Build.VERSION_CODES.KITKAT)
private String getRemovablePath(){
String secondaryStore = System.getenv("SECONDARY_STORAGE");
if (secondaryStore != null){
secondaryStore = secondaryStore.split(":")[0];
secondaryStore += File.separator + "Backups/";
File file = new File(secondaryStore);
if((file.mkdir() || file.isDirectory()) && isFileWritable(secondaryStore)){
return secondaryStore;
} else {
secondaryStore = null;
}
}
// try again by fix address
if(secondaryStore == null){
if (new File("/Removable/MicroSD/").exists()){
secondaryStore = "/Removable/MicroSD/";
} else if( new File("/storage/extSdCard/").exists()){
secondaryStore = "/storage/extSdCard/";
} else if( new File("/storage/sdcard1/").exists()){
secondaryStore = "/storage/sdcard1/";
} else if( new File("/storage/usbcard1/").exists()){
secondaryStore = "/storage/usbcard1/";
} else if( new File("/storage/external_SD/").exists()){
secondaryStore = "/storage/external_SD/";
}
/** add more fix addresses you know */
secondaryStore += "Backups/";
File file = new File(secondaryStore);
if((file.mkdir() || file.isDirectory()) && isFileWritable(secondaryStore)){
return secondaryStore;
} else {
secondaryStore = null;
}
}
/** Try data folder*/
if(secondaryStore == null){
int ver = Build.VERSION.SDK_INT;
File[] externalRoots = null;
if(ver <= Build.VERSION_CODES.JELLY_BEAN_MR2){
externalRoots = ContextCompat.getExternalFilesDirs(getBaseContext(), null);
} else {
externalRoots = getExternalFilesDirs(null);
}
if(externalRoots.length > 1){
secondaryStore = externalRoots[1].getAbsolutePath() + File.separator;
return secondaryStore;
} else {
secondaryStore = null;
}
}
return secondaryStore;
}
please check the link, where present issue:
issue
for access to external memory in previous android versions there is no problem. current possess improvements
Android API < 23
Your Android Manifest must declare the specific user permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You also have to declare the reading permission if you also intend to read files:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
User permissions must be placed before the application section, like this:
<manifest>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
...
<application>
Source of my explanation and examples on how to save files can be found in the official documentation.
Android 6 (API 23)
Things get a bit different starting with Android API 23 because user permissions have to be asked to the user in runtime when needed. A valid answer to this was already given here.
SAF is only needed if you have to write to any location on the SD Card. To write to your app-specific directory on the SD Card, you can use context.getExternalFilesDirs. One of the paths returned will be the path of the your app specific folder on the SD Card.
Again, this is manufacturer dependent as well. If the manufacturer has not set the SECONDARY_STORAGE environment variable, the paths returned by getExternalFilesDirs will not contain the SD Card path.

Where should I choose to save text file in android?

I hope to export my data as a text file and save it to disk in Android, so I need to choose which folder I will save the file to.
I hope that a normal user can find the folder easily and the app does not need special permission to create the folder.
I have read some document, it seems that there are 3 ways: Context.getFilesDir().getAbsolutePath(), Environment.getExternalStorageDirectory().getAbsolutePath() and Context.getExternalFilesDir(null).
You know some android users don't install SD card, so it seems that Environment.getExternalStorageDirectory().getAbsolutePath() and Context.getExternalFilesDir(null) are be excluded.
Am I only to choose Context.getFilesDir().getAbsolutePath()? or is there a better way? Thanks!
BTW, From the document Android - Where to save text files to?
Save it in internal phone storage, here no users and applications can access these files(unless if phone is rooted). But these files will be deleted one's the user selectes clear data from Settings -> Apps -> .
It seems that normal users can't access the saved text files if I use Context.getFilesDir().getAbsolutePath(), is it right?
Use this if you want a path that the user can modify and can have access
getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
More documentation here.
EDIT:
This is how use in case error in some devices:
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
String fname = "TEXT.txt";
File file = new File(path, fname);
if (!path.exists()) {
//noinspection ResultOfMethodCallIgnored
path.mkdir();
}
// YOUR CODE FOR COPY OR CREATE THE FILE TXT in PATH WITH THE VARIABLE file ABOVE

Unable to read directories or files from a sd card

I am new to android development and I have tried to read a directory from my sd card but didn't got succeeded. Below is the code which I wrote to achieve it
File sdcard = Environment.getExternalStorageDirectory();
if(sdcard.exists()) {
Log.d("Sd card", "Sd card exist");
File[] file_names = sdcard.listFiles();
for(File x : file_names) {
Log.d("File Name",x.getName());
}
}
Control passed the if condition and then I got an NullPointerException at "for each" loop line. Probably function sdcard.listFiles() is returning null. I have an Sd card with many folders and files. Actually I have to create a directory file object for directory "Attachments" which is available on my sd card. I also tried the following code to achieve the same.
File file = new File(android.os.Environment.getExternalStorageDirectory() + File.separator + "Attachments");
and
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Attachments");
on both code when I called the function file.exists(), it returned false.
I have also checked whether sd card is mounted or not by the following code.
String sdCardAvail = Environment.getExternalStorageState();
if(sdCardAvail.equals(Environment.MEDIA_MOUNTED))
Log.d("Card status", "Sd card Available");
The above code has printed "Sd card Available" at log cat.
So please help me out to know whether I am doing it correct or missing any thing.
Thanks....
In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGEorWRITE_EXTERNAL_STORAGE system permissions. For example:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
If you need to both read and write files, then you need to request only the WRITE_EXTERNAL_STORAGE permission, because it implicitly requires read access as well.
Also See This Documentation. It Will solve all your future regarding Storage problems.

Categories

Resources