在Android中,检查是否SQLite数据库存在失败不时 [英] In Android, check if sqlite database exists fails from time to time

查看:226
本文介绍了在Android中,检查是否SQLite数据库存在失败不时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Android的我用下面的方法,看看是否SQLite数据库存在,如果我可以打开它并使用它。

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

现在的问题是,我得到来自用户的报告说,他们的数据已经被消灭了和调查的时候,我可以看到数据库替换为资产数据库。所以由于某些原因,即使用户已有一个数据库文件有时SQLiteDatabase.openDatabase()引发错误。我一直无法重现的问题我自己,但它似乎发生了一些用户。

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

这篇关于在Android中,检查是否SQLite数据库存在失败不时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆