Ruwan Liyanage
Ruwan Liyanage

Reputation: 375

How to get the SQLite database instance reference from the Room database?

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.

Upvotes: 1

Views: 2367

Answers (1)

MikeT
MikeT

Reputation: 57043

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);
}

Additional

Regarding the comment :-

Cursor c = db.rawQuery("SELECT * FROM "+tableName+" WHERE 0", null); columnNames = c.getColumnNames(); The tableName comes as function parameter. I could not find any resource how to do it using Room, without re-initiating the database as you suggested in second example.

Then you could use one of the SupportSQLiteDatabase's query methods e.g. :-

    sdb = db.getSQliteDB();

    Cursor csr = sdb.query("SELECT * FROM " + tablename + " WHERE 0");
    String[] columnNames = csr.getColumnNames();
    }
    csr.close();

If you use RoomDatabase's rawQuery method then you have to know the column names and have an object that has member variables that match the column names.

Upvotes: 4

Related Questions