您的位置:首页 > 移动开发 > Android开发

android 使用外部sqlite数据库

2017-12-04 15:41 239 查看
因为在项目中需要使用外部数据库的数据,找了好多资料,最终实现效果的版本,记录下过程 

首先,把xxx.db的数据库文件放到res下面的raw文件夹下面

然后复制数据库代码如下

public static boolean copyRawDBToApkDb(Context context, int copyRawDbResId, String apkDbPath, String dbName, boolean refresh)
throws IOException {
boolean b = false;

File f = new File(apkDbPath);
if (!f.exists()) {
f.mkdirs();
}

File dbFile = new File(apkDbPath + dbName);
b = isDbFileExists(dbFile, refresh);

OutputStream outputStream = null;
InputStream inputStream = null;
try {
if (!b) {

inputStream = context.getResources().openRawResource(copyRawDbResId);
outputStream = new FileOutputStream(dbFile);

byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
while (len > 0) {
outputStream.write(buffer, 0, len);
len = inputStream.read(buffer);
}
//写完后刷新
outputStream.flush();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (inputStream != null) {//关闭流,释放资源
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}

}
return !b;
}

在启动页,调用复制数据库方法 

private void copyRawDB() {
try {
// 拷贝res/raw/xxxx.db 到/data/data/com.bj**.oo/databases/ 目录下面
boolean isSuccess = DBUtils.copyRawDBToApkDb(MainActivity.this, R.raw.student, DBUtils.APK_DB_PATH, DBUtils.ECMC_DB_NAME, true);
selDBData();
} catch (IOException e) {

}
}


因为在项目中使用的greenDao数据库工具,所以注意,需要把数据库版本改为和外部数据库的版本一致。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: