我有一个扩展 ProviderTestCase2<> 的测试类。
我想用一些 .db 文件中的数据填充这个测试类数据库。
是否有一些特定的方法可以将一些 .db 文件推送到 ProviderTestCase2 的模拟上下文中?
否则哪种方式更容易从 .db 文件填充数据库?!
非常感谢!!
最佳答案
如何从 SD 卡或类似的东西中复制一个预先存在的 .db 文件?这是一段可以为您完成此操作的快速代码:
private void importDBFile(File importDB) {
String dataDir = Environment.getDataDirectory().getPath();
String packageName = getPackageName();
File importDir = new File(dataDir + "/data/" + packageName + "/databases/");
if (!importDir.exists()) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
return;
}
File importFile = new File(importDir.getPath() + "/" + importDB.getName());
try {
importFile.createNewFile();
copyDB(importDB, importFile);
Toast.makeText(this, "Import Successful", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
Toast.makeText(this, "There was a problem importing the Database", Toast.LENGTH_SHORT).show();
}
}
private void copyDB(File from, File to) throws IOException {
FileChannel inChannel = new FileInputStream(from).getChannel();
FileChannel outChannel = new FileOutputStream(to).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
希望这对你的场景有用
关于android - 如何在 Android 中填充测试数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3257856/