Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file from external storage in Android

Tags:

file

android

This could probably be a fast fix but currently I am unable to get this working...

I have an asynctask where I am parsing a XML file. If I place an XML file in the assets folder i can open and parse it no problem.

But if I try to open a XML file from external storage it fails.

Here is my asynctask:

private class async extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
    while (!isCancelled()) {

     try {
         NodeList nList;
         Node node;

         InputStream is = getAssets().open("file.xml");
         // this works

         File is = new File("/storage/emulated/0/test.xml");
         // this fails

         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
         Document doc = dBuilder.parse(is);

I am getting this error:

I/System.out: File path: /storage/emulated/0/test.xml
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/test.xml (Permission denied)

These permissions are in my manifest:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Could someone tell me why I am getting this error?

Thanks!

like image 363
Bavilo Avatar asked Oct 29 '25 20:10

Bavilo


1 Answers

I see your error message :

java.io.FileNotFoundException: /storage/emulated/0/test.xml (Permission denied)

Remember that running on running Android 6.0 you must implement runtime permissions before you try to read or write the external storage.

setting this into your manifest.xml is not enough for devices with Android 6.0+:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
like image 105
Jorgesys Avatar answered Oct 31 '25 10:10

Jorgesys