-1

I am trying to backup an android sqlite db. if i run the code one folder is created as i given in program.But that folder is empty,Please help me backup my database and how can i view it. Am using Firefox sqlite manager.Help me to backup my db when i click a button backup db.

My code:

public void exportDatabase(String databaseName) {

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

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
            String backupDBPath = "PRIM.sqlite";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);
            System.out.println("@@ Enter 12222222222222");
            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();
                System.out.println("@@ Enter 2");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
harinee rr
  • 29
  • 7
  • Have you requested permission to write to external storage? Also, print out the `currentDB` and `backupDB` paths and make sure they are correct – Elvis Chweya Sep 13 '17 at 11:34
  • try https://stackoverflow.com/a/13504743/4146722 – Pratik Tank Sep 13 '17 at 11:36
  • Possible duplicate of [Android backup/restore: how to backup an internal database?](https://stackoverflow.com/questions/5282936/android-backup-restore-how-to-backup-an-internal-database) – araknoid Sep 13 '17 at 12:01

2 Answers2

0

Looks like you are trying to write to an external storage like SD card. You will need to have permissions for that in manifest or during run time.

https://developer.android.com/training/basics/data-storage/files.html#GetWritePermission

Sanjeev
  • 141
  • 2
0

this is how I capture the path to the EXTERNAL SD CARD on a tablet it should work for all devices that have a SD CARD

       File removable = ContextCompat.getExternalFilesDirs(this, null)[1];
       THE_PATH = String.valueOf(removable)

THE_PATH is a Public Static String so I can use it in my DBHelper as of now I capture this path on the loader Activity

Vector
  • 3,066
  • 5
  • 27
  • 54