在程序的中我從assets中復制了SQLite數據庫,可以使用。當把程序第一次安裝在仿真器中運行時,獲得以下錯誤。
Failed to open the database. closing it.
android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file
E/SQLiteDatabase(7516): at android.database.sqlite.SQLiteDatabase.dbopen(Native Method)
E/SQLiteDatabase(29308): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1013)
E/SQLiteDatabase(29308): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
E/SQLiteDatabase(29308): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
E/SQLiteDatabase(29308): at com.guayama.database.URLDatabaseHelper.checkDBExists(URLDatabaseHelper.java:86)
E/SQLiteDatabase(29308): at com.guayama.database.URLDatabaseHelper.createURLDB(URLDatabaseHelper.java:54)
E/SQLiteDatabase(29308): at com.guayama.database.URLDatabaseHelper.<init>(URLDatabaseHelper.java:38)
打開數據庫用的代碼:
SQLiteDatabase.openDatabase(mPath, null,SQLiteDatabase.CREATE_IF_NECESSARY);
也試過以下的代碼打開:
checkDB = SQLiteDatabase.openDatabase(mPath, null,
SQLiteDatabase.OPEN_READONLY);
還有這個代碼片段:
SQLiteDatabase.openDatabase(mPath, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);
可以幫我看下問題所在嗎?謝謝!
我經常用下面的步驟從assets文件夾中復制數據庫
private void copyDatabase() throws IOException{
InputStream inputStream = context.getAssets().open(DB_NAME);
String dbCreatePath = DB_PATH+DB_NAME;
OutputStream outputStream = new FileOutputStream(dbCreatePath);
byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer))>0){
outputStream.write(buffer,0,length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
然後我會用下面的方法檢查一遍:
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try {
String dbPath = DB_PATH+DB_NAME;
checkDB = SQLiteDatabase.openDatabase(dbPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// TODO: handle exception
}
if(checkDB!=null){
checkDB.close();}
return checkDB != null ? true:false;
}