Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backup SQLite Database in Android

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.

like image 480
Mohammedsalim Shivani Avatar asked Oct 16 '22 10:10

Mohammedsalim Shivani


1 Answers

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();
        }

    } 
like image 152
astric mobiles Avatar answered Oct 29 '22 23:10

astric mobiles