Bugdr0id
Bugdr0id

Reputation: 3063

Cant find database when app starts

Im trying to do a simple example using my own SQLite database, android and greenDAO generator to generate classes for my android app.

My database file is defined this way:

1) Create a database called "OneTableDB" (without extension, SQLite 3) with the following structure:

Entity: Professor

Entity: android_metadata

Then i populated android_metadata with the value 'en_US', and the entity with few rows.

2) placed on my Android app structure inside: proj_root/databases/ Full path to database file: proj_root/databases/OneTableDB

3)i have a method to check whether database exists or not (in my case, it has to exist, since i placed inside databases folder)

private boolean databaseExists() {
    SQLiteDatabase sqliteDatabase = null;
    try {
        String databasePath = DB_PATH + DB_NAME;

        File f = new File(DB_PATH + DB_NAME);
        f.exists();

        sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
                SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        e.printStackTrace();
    }

    if (sqliteDatabase != null) {
        sqliteDatabase.close();
    }
    return sqliteDatabase != null ? true : false;
}

//DB_PATH = /data/data/com.myapp.android_dao_tests/databases/

//DB_NAME = OneTableDB

debugging on f.exists(), it returns false value and then breaks on

sqliteDatabase = SQLiteDatabase.openDatabase(databasePath, null,
                SQLiteDatabase.OPEN_READONLY);

During the debugging i used adb shell to check if the path was right, and in fact i can navigate to /data/data/com.myapp.android_dao_tests/ and there is no databases folder!

Any idea how can i solve this problem?

Thanks in advance?

Upvotes: 0

Views: 97

Answers (1)

PaF
PaF

Reputation: 3477

The DB "template" is saved in the assets/ folder, in order for it to be bundled in the apk. The code then copies the DB from assets/ to databases/ to make it accessible as a regular SQLite DB.

After further investigation, it seems like Android refuses to acknowledge the new DB as its own. Apparently, the built-in DB mechanism wasn't meant to be used this way.

The correct way to approach it is by keeping the data in textual format in assets/ so that if the app starts and finds there's no DB, it will create the schema itself, and populate it with the data in the text files from the assets/ folder.

Upvotes: 1

Related Questions