0

I am using Room DB to save data locally in android.

Now, I want to preserve the data even user uninstall the application or do clear storage.

So, I created Room DB in following location.

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getPath()

Everything works fine.

But if I clear the storage or uninstall the application and I open the application again, I am getting following error.

Caused by: java.util.concurrent.ExecutionException: android.database.sqlite.SQLiteCantOpenDatabaseException: Cannot open database '/storage/emulated/0/Download/database/hhcf': File /storage/emulated/0/Download/database/hhcf is not readable

This issue coming in Android 11. For Android 9 no excetion is there.

I have granted following permissions as well.

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

And,

android:requestLegacyExternalStorage="true"

in application tag.

Any help would be appreciated.

Jay Vyas
  • 2,674
  • 5
  • 27
  • 58

1 Answers1

1

You need to request user permission to get this permission, adding it only in manifest won't work, at least it didn't for me. I did something like this:

    @RequiresApi(api = Build.VERSION_CODES.R)
public void checkFileAccessPermission() {
    if (Environment.isExternalStorageManager()) {
        return;
    }
    Intent getPermission = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
    startActivityForResult(getPermission, 123);
}

It's a solution from this thread: How to obtain MANAGE_EXTERNAL_STORAGE permission

But remember that if you want your app to be on the google play store you need to justify to google why you need this permission like this article says: https://support.google.com/googleplay/android-developer/answer/10467955?hl=en

If you use another path for files e.g method getFilesDir() you won't have this problem either, but it's only good if developing a new app, or something like that.