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

前提是你 提交于 2019-11-27 11:22:41

问题


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?


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



回答2:


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


来源:https://stackoverflow.com/questions/8007993/in-android-check-if-sqlite-database-exists-fails-from-time-to-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!