【发布时间】:2020-04-28 09:12:29
【问题描述】:
我有一个本地 sqlite 数据库保存在资产中,当应用程序打开时,它将被复制。当数据库有新版本时,应该替换旧文件。所以我所做的只是再次复制文件。这种方法在模拟器上没有问题,我成功更新了数据库。但是在真机上,数据库复制失败。
我正在使用下面的代码来初始化数据库
initDb() async {
// Construct a file path to copy database to
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'dictionary');
// Only copy if the database doesn't exist
if (FileSystemEntity.typeSync(path) == FileSystemEntityType.notFound) {
// Load database from asset and copy
ByteData data = await rootBundle.load(join('assets', 'dictionary'));
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Save copied asset to documents
await new File(path).writeAsBytes(bytes);
}
var theDb = await openDatabase(path, version: 4, onUpgrade: _onUpgrade);
return theDb;
}
这是我的onUpgrade
void _onUpgrade(Database db, int oldVersion, int newVersion) async {
var batch = db.batch();
if (oldVersion < newVersion) {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "dictionary");
ByteData data = await rootBundle.load(join('assets', 'dictionary'));
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
// Save copied asset to documents
await new File(path).writeAsBytes(bytes);
}
await batch.commit();
}
出了什么问题?
【问题讨论】: