1
我有一个应用程序需要访问资产文件夹数据库来获取应用程序启动时的数据,所以我从资产动作中做了一些复制数据,但在上一版中,用户说无法打开应用程序,因此有些用户可以。Android复制数据库目录问题?
我可以知道,如果我需要将数据库从assets文件夹复制到用户设备,我应该使用哪个数据库目录路径来存储复制的数据库?或者在我的代码中缺少一些重要的东西?
像现在这样,我只是在做这个设备上:
createDirectory:
public boolean createDirectory() {
if(Environment.getExternalStorageState().contains(Environment.MEDIA_MOUNTED))
{
String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath()+GlobalConfig.CONFIG_DATA_DIR;
if(isNeedDL(rootPath)) {
File myDir = new File(rootPath);
return myDir.mkdirs();
}
}
return false;
}
和数据库目录,其中GlobalConfig.CONFIG_DATA_DIR = “/数据/”
path = Environment.getExternalStorageDirectory().getAbsolutePath()+GlobalConfig.CONFIG_DATA_DIR;
和SQLiteOpenHelper类:检查数据库是否退出,执行复制操作。
private NOLDatabaseHelper(Context context, String path) {
super(context, path + DB_NAME_OUTDBNAME, null, DB_VERSION);
this.context = context;
}
public void createDatabase() {
if(!isDatabaseExited()) {
Log.v(GlobalConfig.TAG, "NO database");
getReadableDatabase();
copyDataBaseFromAsset();
} else {
Log.v(GlobalConfig.TAG, "Has database");
}
}
public static boolean isDatabaseExited() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME_OUTDBNAME, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
Log.v(GlobalConfig.TAG,"check? "+DB_PATH + DB_NAME_OUTDBNAME+" checkDB:"+checkDB);
} catch (SQLiteException e) {}
return checkDB != null ? true : false;
}
谢谢!
这里是复制功能:
// to fix database is locked issue
private synchronized void copyDataBaseFromAsset()
{
int length = -1;
byte[] buffer = new byte[1024];
AssetManager am = context.getAssets();
try
{
InputStream assetsDB = am.open(DB_NAME_INDBNAME);
String outFileName = DB_PATH + DB_NAME_OUTDBNAME;
OutputStream dbOut = new FileOutputStream(outFileName);
while ((length = assetsDB.read(buffer)) > 0) {
dbOut.write(buffer, 0, length);
}
dbOut.flush();
dbOut.close();
assetsDB.close();
} catch(Exception e) {
Log.e(GlobalConfig.TAG, "copyDataBaseFromAsset error, is say: "+e.toString());
}
}
我在帖子上添加了方法copyDataBaseFromAsset,非常感谢〜 –