Make a backup copy of a database to the sd card

1

I have this simple database and I want to backup the sd card, how can I do it?

public class Usuario extends SQLiteOpenHelper {

    String sql ="CREATE TABLE Cliente (id INTEGER, nombre TEXT, apellido TEXT)";

    public Usuario(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXIST Cliente");
        db.execSQL(sql);
    }
    
asked by Francisco Javier 28.06.2017 в 02:17
source

2 answers

1

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)

    
answered by 13.07.2017 в 23:09
0

The sqlite database is simply a file. You can copy the file to the sdcard without further ado. I copy and paste a piece of code to do it:

public void exportDatabse(String databaseName) {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
                String backupDBPath = "backupname.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                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();
                }
            }
        } catch (Exception e) {

        }
    }

Remember to give write permission:

Link: link

Greetings

    
answered by 29.06.2017 в 18:26