我有一些代码可以将数据库从asset
复制到/data/data
。
当我使用SELECT
查询时,它有效;但是当我使用INSERT
查询时,它会返回一个错误,指出我的数据库是只读的。
我的代码:
public class AssetDatabaseOpenHelper {
private static final String DB_NAME = "database";
private Context context;
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}
}
在我的活动中使用我的课程的代码:
AssetDatabaseOpenHelper adb = new AssetDatabaseOpenHelper(context);
SQLiteDatabase db = adb.openDatabase();
答案 0 :(得分:2)
试试这个:
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
数据库应为OPEN_READWRITE