Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Android, check if sqlite database exists fails from time to time

In Android I use the following method to see if the sqlite database exist and if I can open it and use it.

If it fail this test I copy the database file from the assets (this should only happen once, when the user first start the app).

/*
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch(SQLiteException e) {
        //database does't exist yet.
    }

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

The problem is that I get reports from users saying that their data has been wiped out and when investigating I can see that the database is replaced with the database from the assets. So for some reason even if the user already has a database file sometimes the SQLiteDatabase.openDatabase() throws an error. I haven't been able to reproduce the issue myself but it seems to happen for some users.

Anyone have an idea what the problem might be here? Is there a better way to do this test?

like image 554
Martin Avatar asked Nov 04 '11 10:11

Martin


People also ask

How can I tell if SQLite database is empty Android?

To determine whether an SQLite database file is empty, execute the following query: SELECT COUNT(*) FROM sqlite_schema; You will get the number of objects (tables, indices, views, triggers) in the database or 0 if the file is empty.

Is SQLite still used in Android?

SQLite is another data storage available in Android where we can store data in the user's device and can use it any time when required.


1 Answers

How about just checking the filesystem to see if the database exists instead of trying to open it first?

You could be trying to open a database that is already open and that will throw an error causing you to think it does not exist.

File database=getApplicationContext().getDatabasePath("databasename.db");

if (!database.exists()) {
    // Database does not exist so copy it from assets here
    Log.i("Database", "Not Found");
} else {
    Log.i("Database", "Found");
}
like image 166
Kuffs Avatar answered Sep 17 '22 08:09

Kuffs