1
我想爲我的應用程序中的數據庫進行備份和恢復,以便當用戶刪除應用程序並重新安裝時,他們可以恢復他們的數據。 在Android Studio中執行此操作的最佳方法是什麼?備份和恢復數據庫android studio
我想爲我的應用程序中的數據庫進行備份和恢復,以便當用戶刪除應用程序並重新安裝時,他們可以恢復他們的數據。 在Android Studio中執行此操作的最佳方法是什麼?備份和恢復數據庫android studio
有幾種類型的備份和恢復到您的數據庫文件,如谷歌驅動器,下拉框和一個驅動器。如果您想從本地存儲中進行備份,請嘗試下面的代碼。
備份代碼:
public void backUp() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//your package name//databases//dbname.db";
String backupDBPath = "dbname.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
Log.d("backupDB path", "" + backupDB.getAbsolutePath());
if (currentDB.exists()) {
FileChannel src = new FileInputStream(currentDB).getChannel();
FileChannel dst = new FileOutputStream(backupDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Backup is successful to SD card", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
還原代碼:
public void restore() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//your package name//databases//dbname.db";;
String backupDBPath = "dbname.db";
File currentDB = new File(data, currentDBPath);
File backupDB = new File(sd, backupDBPath);
if (currentDB.exists()) {
FileChannel src = new FileInputStream(backupDB).getChannel();
FileChannel dst = new FileOutputStream(currentDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Database Restored successfully", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}