Search code examples
androidandroid-room

How can I change the default location of a Room database?


I want to change the location of the Android Room Database. I know that the database is inside of the files system, and I need to get root permissions, but I do not want to root my phone.

The idea is change the database location to SD card, and can access it without root my phone


Solution

  • Just put the location path in the name of the database.
    I.e.:

    AppDatabase db = Room.databaseBuilder(getApplicationContext(),
            AppDatabase.class, "database-name").build();
    

    Put the router in database name.
    I.e.:

     AppDatabase db = Room.databaseBuilder(getApplicationContext(),
            AppDatabase.class, "/storage/emulated/0/folder/database-name").build();
    

    and do not forget to give the write permissions to the application

    thx @vitidev

    UPDATE

    If you target Android 10 or higher, set the value of requestLegacyExternalStorage to true in your app's manifest file:

    <manifest ... >
    <!-- This attribute is "false" by default on apps targeting
       Android 10 or higher. -->
     <application android:requestLegacyExternalStorage="true" ... >
    ...
     </application>
    </manifest>