How do I backup a SQLite Database to a SD Card? I have looked at many examples on here and none of them work for me. I have added the following lines to my manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
and the following to a fragment with a textview to click on and perform the backup:
// Find the Text View that displays the Backup Database Button //
TextView backupDatabaseTextView = (TextView) rootview.findViewById(R.id.backup_database_text_view);
// Set a click listener on the backup database text view //
backupDatabaseTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exportDB();
}
});
and the following method:
private void exportDB() {
try {
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
if (sd.canWrite()) {
String currentDBPath = "//data//" + "com.budgettrackpro.android.budgettrackpro"
+ "//databases//" + "budgettrackpro.db";
String backupDBPath = "BudgetTrackPro";
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(getActivity(), "Backup Successful!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Backup Failed!", Toast.LENGTH_SHORT)
.show();
}
}