Search code examples
javaandroiddatabaserealm

My App is crashing on android 11 when I store realm database locally in a folder?


The app crashes on Android 11 when I am going to save realm database in local internal storage. The app is working in all other version but today I updated my app to android 11 and it's crashing.

E/AndroidRuntime: FATAL EXCEPTION: main
Process:  PID: 7882
io.realm.exceptions.RealmError: Unrecoverable error. open() failed: Operation not permitted in io_realm_internal_Group.cpp line 210
    at io.realm.internal.Group.nativeWriteToFile(Native Method)
    
   
      private Realm realm;

      try {

        File file = new File(folderPath);
        if (!file.exists()) {
            file.mkdir();
        }
      
        realm = new File(file, fileName);
       
        if (realm .exists()) {
            realm .delete();
        }
       
        realm.writeCopyTo(realm ); // crashing here in this line

    } catch (IOException e) {
        e.printStackTrace();
      
    }

Solution

  • After reading the documentation I solved the issue by replacing getExternalStorageDirectory to context.getExternalFilesDir(); to save realm database locally in a folder for backup.

    See Doc