lcantoral
lcantoral

Reputation: 103

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

Upvotes: 10

Views: 6160

Answers (2)

Ricky Uppal
Ricky Uppal

Reputation: 11

I was also facing the same. I was using same code as @joe06.

The only thing we are missing is that we need to create the directory before calling the Room build.

private fun setUpDirectory() {
        var dbDirectory =
            Environment.getExternalStorageDirectory().absolutePath + "/data/abc/databases/"
        var dbDirFile = File(dbDirectory)
        if (!dbDirFile.exists()) {
            dbDirFile.mkdirs()
        }
    }

Building Room DB after creating directory will create the DB at any location you want.

Upvotes: 1

joe06
joe06

Reputation: 458

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>

Upvotes: 21

Related Questions