Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save files in External Storage Public Directory DOCUMENTS on Android 4.1.2

i want to save a file on my Android 4.1.2 smartphone in the documents directory.

This code snippet:

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"test.txt");

throws this exception:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoSuchFieldError: android.os.Environment.DIRECTORY_DOCUMENTS

While this one is working:

File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"test.txt"); 

But i want to save my file in my documents directory, not in downloads. Ive read DIRECTORY_DOCUMENTS is only available in Android 4.4 and higher. But there is also a documents direcotry on my smartphone. So, is there no solution to save it in documents?

Thx for answers

Pebbles

like image 947
pebbles Avatar asked Jan 20 '15 02:01

pebbles


People also ask

What is external storage directory in Android?

Android External Storage Example Code getExternalFilesDir(): It returns the path to files folder inside Android/data/data/application_package/ on the SD card. It is used to store any required files for your app (like images downloaded from web or cache files).

How do I get write permission for external storage on Android?

To read and write data to external storage, the app required WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE system permission. These permissions are added to the AndroidManifest. xml file. Add these permissions just after the package name.


2 Answers

You are not able to access DIRECTORY_DOCUMENTS becuase it is not there in Android 4.1.2. Which means, though there is a Documents directory in your external storage, it is not pointed to by DIRECTORY_DOCUMENTS (since it is non-existent). To solve this, you have to create the directory if it is not present and get the path to that folder manually.

File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
boolean isPresent = true;
if (!docsFolder.exists()) {
    isPresent = docsFolder.mkdir();
}
if (isPresent) {
    File file = new File(docsFolder.getAbsolutePath(),"test.txt"); 
} else {
    // Failure
}
like image 100
Arjun Avatar answered Oct 06 '22 03:10

Arjun


The folder is present in older Versions (from Api 1) of Android but the field DIRECTORY_DOCUMENTS is available first in Version 4.4 (Api 19 - Kitkat).

Solution for me was to use Environment.getExternalStorageDirectory() + "/Documents" instead DIRECTORY_DOCUMENTS for older Android Versions.

like image 38
iwanlenin Avatar answered Oct 06 '22 04:10

iwanlenin