4

A few months ago, I made an Android app. But in the time, I didn't think that I would ever need to make a backup of my database. The truth is, now I do but I didn't implemented it.

Now, is there anyway for me to make a database backup, without loosing the data? Because I think if I make the method for my database backup, when I build the app, I will loose all the data, since I have this method:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + POINTS_TABLE);
    db.execSQL("DROP TABLE IF EXISTS " + NETWORKS_TABLE);
    onCreate(db);
}
dex90
  • 175
  • 2
  • 2
  • 8

2 Answers2

1

Copy db file to sdcard is one way to backup

public static void copyFileInSDCard () {

    try {
        File sd = Environment.getExternalStorageDirectory ();
        File data = Environment.getDataDirectory ();

        if (sd.canWrite ()) {
            String DATABASE_NAME = "YOURDBNAME";
            String currentDBPath = "//data//your.package//databases//" + DATABASE_NAME;
            String backupDBPath = "FILE[Name]";
            File currentDB = new File (data, currentDBPath);
            File backupDB = new File (sd, backupDBPath);

            if (currentDB.exists ()) {
                @SuppressWarnings("resource")
                FileChannel src = new FileInputStream (currentDB).getChannel ();
                @SuppressWarnings("resource")
                FileChannel dst = new FileOutputStream (backupDB).getChannel ();
                dst.transferFrom (src, 0, src.size ());
                src.close ();
                dst.close ();
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace ();
    }
}
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
0

The solution provided by @yuvaツ worked

If your device is running Android v4 or above, you can pull app data, including it's database, without root by using adb backup command, then extract the backup file and access the sqlite database.

First backup app data to your PC via USB cable with the following command, replace app.package.name with the actual package name of the application.

adb backup -f ~/data.ab -noapk app.package.name This will prompt you to "unlock your device and confirm the backup operation". Do not provide a password for backup encryption, so you can extract it later. Click on the "Back up my data" button on your device. The screen will display the name of the package you're backing up, then close by itself upon successful completion.

The resulting data.ab file in your home folder contains application data in android backup format. To extract it use the following command:

dd if=data.ab bs=1 skip=24 | openssl zlib -d | tar -xvf - The result is the apps/app.package.name/ folder containing application data, including sqlite database.

For more details you can check the original blog post.

dex90
  • 175
  • 2
  • 2
  • 8