android - 数据库未在 Android 中复制
问题描述
我在我的应用程序的第一次运行时创建了一个数据库并为其播种。有时我需要从外部源更新数据库,所以我必须将它放在 Android 的 Documents 文件夹中并从那里获取它。因此,我使用下面的代码将该数据库从 Documents 文件夹复制到应用程序数据库中。使用调试器,我可以在没有任何错误的情况下完成整个应用程序,也可以在日志中完成。但是,只要我在“data/data/com.myApp.com/databases/dbName.db”中检查应用程序本身的数据库,该数据库就不会得到更新,或者不会复制 Documents 文件夹中的数据库。我还尝试将要复制的数据库放在应用程序的“资产”文件夹中,但我仍然没有得到想要的结果:
主要活动
DatabaseHelper db = new DatabaseHelper(getActivity().getApplicationContext());
db.copyDatabase();
数据库助手
public void copyDatabase() {
DB_FILE = context.getDatabasePath(DB_NAME);
try {
InputStream mInput = mContext.getAssets().open(DB_NAME);
OutputStream mOutput = new FileOutputStream(DB_FILE);
byte[] mBuffer = new byte[1024];
int mLenth;
while((mLenth = mInput.read(mBuffer)) > 0) {
mOutput.write(mBuffer, 0, mLenth);
}
mOutput.flush();
mOutput.close();
mInput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
解决方案
您可以创建一个空数据库,然后将资产中的数据库推送到空数据库,如上述链接中所实现的那样:
public class DBHandler extends SQLiteOpenHelper {
protected static final String DATABASE_NAME_PRODUCTION = "productionComments.db";
private Context context;
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, DATABASE_VERSION);
this.context = context;
}
//copy database from assets folder (.sqlite) file to an empty database
public void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open("prod.db");
// Path to the just created empty db
String outFileName = "/data/data/com.qarun.qpcbeta/databases/"+DATABASE_NAME_PRODUCTION;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
注意:/data/data/com.qarun.qpcbeta/databases/
您可以使用getDatabasePath()
.
推荐阅读
- protractor - 使用辅助类中的 this.currentTestState
- r - 参数化查询不适用于 SQL Server 2017
- sql-server - 为什么 DELETE TOP(X) 语句没有删除先前 SELECT TOP(X) 返回的相同记录?
- javascript - 嵌入式视频 (Vimeo) 页面加载优化
- python - 如何将所选元素与行中的总和值相除,对角线 PANDAS 上的值除外
- javascript - 如何从javascript中的函数返回值
- javascript - 返回模式最后一次出现的编号
- node.js - 无法读取日志文件的行
- spring-boot - 如何在没有spring boot gradle插件的情况下在gradle中使用spring boot
- npm - angular-cli 不断抛出错误:找不到模块'source-map'