Search code examples
javaandroidsqldatabaseandroid-sqlite

SQLlite Tables Empty when reopen android app


I can see before closing my app that I have a table called 'styles' inside my SQLite database. The table has multiple entries. However once I close my app and reopen it, if I do a raw query "SELECT * FROM styles", no results are returned.

I create my SQLiteDatabase by:

SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(getDatabaseDirectory(), null);
boolean hasEntries = database.rawQuery("SELECT * FROM styles", new String[]{}).moveToFirst();
// hasEntries is always false
...
database.close()

The method getDatabaseString() is implemented as so:

private File getDatabaseDirectory() {
        File dbpath = this.context.getDatabasePath( "MyAppsDatabase" );
        if (!dbpath.getParentFile().exists()) {
            dbpath.getParentFile().mkdirs();
        }
        return dbpath;
}

This is being run on a thread other than the UI thread, incase that has any effect? I have seen some examples where individuals are overriding there database directory when getting the database path, but I assume that is not my issue. Any suggestions would be very helpful. Thank you!


Solution

  • Instead of creating my database instance using SQLiteDatabase.openOrCreateDatabase(...) I created a SQLiteOpenHelper folowing the instruction found here:

    https://developer.android.com/training/data-storage/sqlite

    Calling sqLiteOpenHelper.getWritableDatabase() sorts the issue.