Skip to content

Instantly share code, notes, and snippets.

@viveknavadia
Last active September 29, 2016 07:54
Show Gist options
  • Save viveknavadia/6c6c45a74f1482bf48ea751807bbbc12 to your computer and use it in GitHub Desktop.
Save viveknavadia/6c6c45a74f1482bf48ea751807bbbc12 to your computer and use it in GitHub Desktop.
Various utilities functions for android.

Utils.java

Function Description
[Database Backup](#database backup) Utility function to backup database in sdcard

database backup

/**
 * Save database to external storage
 *
 * @param packageName  application package name
 * @param databaseName database name
 */
public static boolean backupDatabaseToSdcard(Context context, String packageName, String databaseName) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//" + packageName + "//databases//" + databaseName;
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, databaseName);
            Logger.d("current database path: %s %nbackup database path: %s", currentDB, backupDB);
            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();
            }
            Logger.d("database backed up...");
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment