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

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

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&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");
}

Answer:

I want to share a method to check if database exists:
Give me a +1 if it runs fine for you,
Thanks.

private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {

        File database=myContext.getDatabasePath(DB_NAME);

        if (database.exists()) {

            Log.i("Database", "Found");

            String myPath = database.getAbsolutePath();

            Log.i("Database Path", myPath);

            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        } else {                

            // Database does not exist so copy it from assets here
            Log.i("Database", "Not Found");

        }

    } catch(SQLiteException e) {

        Log.i("Database", "Not Found");

    } finally {

        if(checkDB != null) {

            checkDB.close();

        }

    }

    return checkDB != null ? true : false;
}