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,非常感謝〜 –