openOrCreateDatabase失败

时间:2014-02-08 13:02:00

标签: android sqliteopenhelper

我有SQLLite数据库创建的问题。我检查了db是否存在,关闭数据库连接。但我不明白我失败的地方或openOrCreateDatabase失败。

...
public class DBHelper extends SQLiteOpenHelper {
...
public DBHelper(Context context) {
    super(context, DBName, null, version);
    currentContext = context;
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),context.getString(R.string.cache_dirname));
    else
        cacheDir=context.getCacheDir();     
    if(!cacheDir.exists())
        cacheDir.mkdirs();
    DBPath=cacheDir.toString()+"/"; 
    createDatabase();
}

private void createDatabase() {
    boolean dbExists = checkDbExists();
    if (dbExists) {
        // do nothing
    } else {
                    // **fails here**           
        DB = currentContext.openOrCreateDatabase(DBName, 0, null);
        ...         
    }
}

private boolean checkDbExists() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DBPath + DBName;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        Log.d("","database doesn't exists");
    }
    if (checkDB != null) {
        checkDB.close();
    }
    return checkDB != null ? true : false;
}

}

错误

Failed to open databse '/storage/emulated/0/My_test/dbtest'
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error code (14): Couldn't open database

失败在哪里?

2 个答案:

答案 0 :(得分:1)

试试这个

DBPath = Environment.getDataDirectory().getName()+"//data//com.your.package//databases//";

String myPath = DBPath + DBName;

答案 1 :(得分:1)

它的失败是因为您在默认位置打开数据库,同时在另一个位置创建目录并检查数据库。

DB = currentContext.openOrCreateDatabase(DBName, 0, null);

“DBName”应该是数据库的完整路径,或者它将在默认位置创建。这是我用来打开变量位置数据库的代码。

SQLiteDatabase m_db = context.openOrCreateDatabase(
        db_file.getAbsolutePath(), Context.MODE_PRIVATE, null, null);

将路径+“/”+ dbname组合成一个完整路径,或者您可以将包含正确路径的文件传递给它并使用get绝对路径。

编辑:我注意到你实际上是在打开数据库来检查它是否存在。这将演示如何检查数据库是否存在,对于可变位置:

 File db_file = new File(folder, dbName);
 boolean dbExists = db_file.exists();