copy database file to sdcard in android

后端 未结 2 672
梦谈多话
梦谈多话 2020-11-30 06:34

I am getting my database file by this code

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


        
2条回答
  •  旧巷少年郎
    2020-11-30 07:20

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

提交回复
热议问题