There is no method within the class SQLiteOpenHelper
to perform a backup, for this you need to make a copy of the database and add it to your sdcard, you can use this method,
public static boolean copiaBD(String from, String to) {
boolean result = false;
try{
File dir = new File(to.substring(0, to.lastIndexOf('/')));
dir.mkdirs();
File tof = new File(dir, to.substring(to.lastIndexOf('/') + 1));
int byteread;
File oldfile = new File(from);
if(oldfile.exists()){
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(tof);
byte[] buffer = new byte[1024];
while((byteread = inStream.read(buffer)) != -1){
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
result = true;
}catch (Exception e){
Log.e("copyFile", "Error copiando archivo: " + e.getMessage());
}
return result;
}
Firstly, we obtain the path where the database is located:
String pathDB = getDatabasePath(NOMBRE_DATABASE).toString();
with this path, you indicate the destination of the file to be copied:
copiaBD(pathDB,
Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + getPackageName() + "/" + <nombre archivo destino>);
Do not forget to add permission to write to external storage:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If the operating system is Android 6.0 or later, you have to manually require permissions.
Error showing the external file directory in an AlertDialog in android 6.0 (READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE)