Skip to content Skip to sidebar Skip to footer

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 shou

Solution 1:

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

Solution 2:

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

privatebooleancheckDataBase() {

    SQLiteDatabasecheckDB=null;

    try {

        File database=myContext.getDatabasePath(DB_NAME);

        if (database.exists()) {

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

            StringmyPath= 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;
}

Post a Comment for "In Android, Check If Sqlite Database Exists Fails From Time To Time"