Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy database file to sdcard in android

I am getting my database file by this code

  File dbFile=getDatabasePath("EdsysEyfsDB.db");
               Log.v("database name checking", dbFile.toString());

I want to copy this database file to sdcard so I can do some operation for that. But I can't do any operation on that. The below code is using for copy to sd card

         if (dbFile.exists()) {
                       InputStream inStream = new FileInputStream(dbFile);
                       String file = Environment.getExternalStorageDirectory().getPath()
                            +"/" + "database.db";
                       Log.d("file name checking in  dbFilecondition", file);
                       FileOutputStream fs = new FileOutputStream(file);
                       byte[] buffer = new byte[1444];
                       while ((byteread = inStream.read(buffer)) != -1) {
                           bytesum += byteread;
                           fs.write(buffer, 0, byteread);
                       }
                       inStream.close();
                       fs.close();
                   }

But I am not going in this condition.The database file name is coming properly on LogCat. I already give permission for Read and Write file.

like image 294
Ameer Avatar asked Sep 30 '13 11:09

Ameer


2 Answers

Try this hope this helps you

public void exportDatabse(String databaseName) {
        try {
            File sd = Environment.getExternalStorageDirectory();
            File data = Environment.getDataDirectory();

            if (sd.canWrite()) {
                String currentDBPath = "//data//"+getPackageName()+"//databases//"+databaseName+"";
                String backupDBPath = "backupname.db";
                File currentDB = new File(data, currentDBPath);
                File backupDB = new File(sd, backupDBPath);

                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();
                }
            }
        } catch (Exception e) {

        }
    }

How to call

exportDatabse("YourDBName");

NOTE :

Remember to add permission to write to external storage with <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />, otherwise sd.canWrite() will be false.

like image 107
Biraj Zalavadia Avatar answered Oct 31 '22 20:10

Biraj Zalavadia


Unfortunatelly, the accepted answer is not relevant for these days. The problem is on wrong detected SD path. Actual path usually depends on manufacterer of mobile device and could be different on different models.

I figured out a simple solution to detect an actual path to SD independently of android version, ContextCompat.getExternalFilesDirs[1] contains a relevant string. Tested on devices with android 6 till 9 version

The second one trouble is defined path to DB. It should contains "data/data/" before package name like: "/data/data/" + getPackageName() + "/databases/" + dbFilename;

Here the part of code from my project

String sdPath;

    private boolean isSDPresent(Context context) {

        File[] storage = ContextCompat.getExternalFilesDirs(context, null);
        if (storage.length > 1 && storage[0] != null && storage[1] != null) {
            sdPath = storage[1].toString();
            return true;
        }
        else
          return false;
    }


    private boolean isContextValid(Context context) {
        return context instanceof Activity && !((Activity) context).isFinishing();
    }

    public boolean exportDatabase(Context context, String localDbName, String backupDbName) {
        if (isContextValid(context))
            try {
                if (!SettingsFile.isSDPresent(context)) {
                    Log.e(TAG, "SD is absent!");
                    return false;
                }

                File sd = new File(sdPath); 

                if (sd.canWrite()) {

                    File currentDB = new File("/data/data/" + context.getPackageName() +"/databases/", localDbName); 
                    File backupDB = new File(sd,  backupDbName);

                    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();
                    }
                }
                else {
                    Log.e(TAG, "SD can't write data!");
                    return false;
                }
            } catch (Exception e) {

            }
        else {
            Log.e(TAG, "Export DB: Context is not valid!");
            return false;
        }

        return true;
    }
like image 2
Dimon Avatar answered Oct 31 '22 20:10

Dimon