Save Database on SD Card Backup DB on SD

suggest change
public static Boolean ExportDB(String DATABASE_NAME , String packageName , String folderName){
    //DATABASE_NAME including ".db" at the end like "mayApp.db"
    String DBName = DATABASE_NAME.substring(0, DATABASE_NAME.length() - 3);
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ packageName +"/databases/"+DATABASE_NAME; // getting app db path

    File sd = Environment.getExternalStorageDirectory(); // getting phone SD card path
    String backupPath = sd.getAbsolutePath() + folderName; // if you want to set backup in specific folder name
        /* be careful, folderName must start like this: "/myFolder". Don't forget "/" at the beginning of the folder name.
            You could define folderName like this: "/myOuterFolder/MyInnerFolder" and so on.
        */
    File dir = new File(backupPath);
    if(!dir.exists()) // if there was no folder at this path, it creates it.
    {
        dir.mkdirs();
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
    Date date = new Date();
        /* use the date in the file name to arrange the backups and avoid two files with the same name */
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(backupPath, DBName +"("+ dateFormat.format(date)+").db");
    try {
        if (currentDB.exists() && !backupDB.exists()) {
            source = new FileInputStream(currentDB).getChannel();
            destination = new FileOutputStream(backupDB).getChannel();
            destination.transferFrom(source, 0, source.size());
            source.close();
            destination.close();
            return true;
        }
        return false;
    } catch(IOException e) {
        e.printStackTrace();
        return false;
    }
}

Call this method this way. If transferFrom throws, the channels are not closed. The sample does not request storage permission.

ExportDB("myDB.db", "com.example.exam", "/myFolder");

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents