close
有時候遇到手機無法root成功,導致無法取得到程式的資料庫,
這個時候只能將資料庫搬到記憶卡或我們可以容易取的資料的位置,
這樣就可以拿到資料庫啦!
那來說明一下移動資料庫的方法吧!
首先,要先在manifest.xml檔中加入權限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我是一次將讀取跟寫入記憶卡的權限都加入,這樣如果我要讀取記憶卡的時候就不用再加一次了!
再來就是java程式碼的部分囉!
private void exportDB() { try { File sd = Environment.getExternalStorageDirectory(); File data = Environment.getDataDirectory(); if (sd.canWrite()) { String currentDBPath= "//data//" + "PACKAGE_NAME" + "//databases//" + "DATABASE_NAME"; String backupDBPath = "DATABASE_NAME"; File currentDB = new File(data, currentDBPath); //現在資料庫的位置 File backupDB = new File(sd, backupDBPath); //要移動到的位置 FileChannel src = new FileInputStream(currentDB).getChannel(); FileChannel dst = new FileOutputStream(backupDB).getChannel(); dst.transferFrom(src, 0, src.size()); src.close(); dst.close(); Toast.makeText(getBaseContext(), backupDB.toString(), Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG) .show(); } }
紅色字部分要記得換成自己程式的Package name跟資料庫的名字(.db),
這樣就會把資料庫搬到內部儲存空間啦!
如果想要把資料庫搬到特定資料夾下,
只要更改backupDBPath這個地方的位置就可以囉!
如果換新手機想要留著以前資料庫的資料,
可以只用這個方法移動,
拿出資料庫後,放到新手機,
再把資料庫移到程式指定位置就可以囉!
文章標籤
全站熱搜
留言列表