2

I am trying to copy the SQLite database from the data folder to SDCard using Emulator, i am using below code, which i found here.

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

    if (sd.canWrite()) {
        String currentDBPath = "\\data\\PackageName\\databases\\myDB.db";
        String backupDBPath = "myDB.db";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) 
        {
           // code to copy from currentDB  to backupDB 
        }
    }
} catch (Exception e) {
}

For write permission below is also added to manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Issue:

The issue is that the "currentDB.exists()" returns FALSE.

The "currentDB.getAbsolutePath()" returns the path which is "data\data\PackageName\databases\myDB.db"

This is the correct location of the database, because i can find it using Eclipse >> DDMS perspective >> File Explorer

Can somebody help me find the issue why the "currentDB.exists()" returns FALSE?

Thanks for your valuable time & help.

Community
  • 1
  • 1
Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149

1 Answers1

0

Well guys i just removed the ".db" extension & it works now! See the updated code below:

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

    if (sd.canWrite()) {
        String currentDBPath = "\\data\\PackageName\\databases\\myDB";
        String backupDBPath = "myDB";
        File currentDB = new File(data, currentDBPath);
        File backupDB = new File(sd, backupDBPath);

        if (currentDB.exists()) 
        {
           // code to copy from currentDB  to backupDB 
        }
    }
} catch (Exception e) {
}

myDB.db is replaced with "myDB".

Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
  • 1
    It's because you didn't name your DB with the .db extension. You should (for future reference) have a static constant with your DB name somewhere and reference it with `Main.DATABASE_NAME`. Then you'll need `String currentDBPath = "\\data\\PackageName\\databases\\" + Main.DATABASE_NAME`. This will prevent similar problems. – John Leehey Nov 16 '11 at 17:13