9

I need to make an offline backup of the SQLite database in the mobile's internal storage or the SD Card. But I am clueless, how's this possible.

I followed many threads here on SO, but they suggest copying the DB one location to other, which is not suitable for me, neither to the Google Drive.

Any guidance would be precious.

Mohammedsalim Shivani
  • 1,793
  • 3
  • 19
  • 30

2 Answers2

3

I used this approach.

public string DATABASE_NAME = "YOUR DATABASE NAME HERE";

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

            if (sd.canWrite()) {
                Log.d("TAG", "DatabaseHandler: can write in sd");
                //Replace with YOUR_PACKAGE_NAME and YOUR_DB_NAME
                String currentDBPath = "filepath here"+DATABASE_NAME;
                //Replace with YOUR_FOLDER_PATH and TARGET_DB_NAME in the SD card
                String copieDBPath = DATABASE_NAME;
                File currentDB = new File(data, currentDBPath);
                File copieDB = new File(sd, copieDBPath);
                if (currentDB.exists()) {
                    Log.d("TAG", "DatabaseHandler: DB exist");
                    @SuppressWarnings("resource")
                    FileChannel src = new FileInputStream(currentDB).getChannel();
                    @SuppressWarnings("resource")
                    FileChannel dst = new FileOutputStream(copieDB).getChannel();
                    dst.transferFrom(src, 0, src.size());
                    src.close();
                    dst.close();
                }
            }
        } catch  (Exception e) {
            e.printStackTrace();
        }

    } 
astric mobiles
  • 468
  • 3
  • 14
  • *//Replace with YOUR_PACKAGE_NAME and YOUR_DB_NAME*, no need to hard code package name if you you use `String currentDBPath = context.getDatabasepath(database).getPath();` where context is a Context and database is the database name. – MikeT Nov 12 '18 at 18:52
  • @MohammedsalimShivani restoring from such a file (basically reversing the backup) does work (although you may find that you need to, or that it's simpler to then restart the App). However I'd suggest, when restoring, to initially make a copy of the original DB (so that should the restore fail you can revert to the original DB). – MikeT Nov 12 '18 at 19:16
2

Finally, with this GitHub sample I successfully implemented whatever customization I needed. And it's live now.

Mohammedsalim Shivani
  • 1,793
  • 3
  • 19
  • 30