Home > Software design >  How to get the SQLite database instance reference from the Room database?
How to get the SQLite database instance reference from the Room database?

Time:10-14

I'm trying to get the SQLiteDatabase instance from existing Room database, for using with many complex functions already developed, which are accepting SQLiteDatabase instance as a parameter.

I recently migrated to Room, and decided to keep some time consuming and long processing functions un-affected while a part of my app uses migrated functionalities from Room.(At least until I'm getting more familiar with Room).

I'm not sure is this possible anyway, and it's wonderful if I'm still able to get the SQLite database. I tried following code to retrieve the database, but it gives me a Inconvertible error.

public abstract class Database_ROOM extends RoomDatabase {
    public SQLiteDatabase getSQLiteDB()
    {
        return (SQLiteDatabase) this.mDatabase;
    }
}

above code produces following error. Inconvertible types; cannot cast androidx.sqlite.db.supportSQLiteDatabase to android.database.sqlite.SQLiteDatabase

Is there any other way to get the database, or even is this possible? any help would be highly appreciated.

CodePudding user response:

Is there any other way to get the database, or even is this possible? any help would be highly appreciated.

With room you get a SupportSQLiteDatabase via the RoomDatabase getOpenHelper via the getWritableDatabase method (or getReadableDatabase but you would get a writable database anyway in virtually all situations).

so :-

public SupportSQLiteDatabase getSQliteDB() {
    return this.getOpenHelper().getWritableDatabase();
}
  • Note that a SupportSQLiteDatabase has most (but not all) of the functionality and methods of a SQLiteDatabase.

Alternately if you really wanted an SQLiteDatabase then you could do something like :-

public SQLiteDatabase getSQLiteDB(Context context, String databaseName) {
    return SQLiteDatabase.openDatabase(context.getDatabasePath(databaseName).getPath(),null,SQLiteDatabase.OPEN_READWRITE);
}
  • Related