【问题标题】:Replace sqlite db of my app with backedup db in android 30+将我的应用程序的 sqlite db 替换为 android 30+ 中的备份数据库
【发布时间】:2021-12-13 08:48:27
【问题描述】:

我创建了一个带有 sqlite 数据库的记事本应用程序。该应用程序允许用户将他的数据备份到谷歌驱动器。当用户点击恢复按钮时,我想恢复这些数据。问题是我无法访问 sqlite db 来用谷歌驱动器中的备份文件替换它。

这个问题只发生在 android 29+ 上,如果我将 targetsdk 设置为 28,我的代码可以正常工作。但是google play不允许我上传targetsdk低于30的应用程序,所以我不得不增加sdk版本。 这是我的代码,任何建议都将不胜感激:

File data = Environment.getDataDirectory();
    String currentDBPath = "/data/" + getPackageName() + "/databases/" + Constants.dataBaseName;
    File currentDB = new File(data, currentDBPath);

    String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Constants.dataBaseName;
    File destination = new File(destinationPath);
try {
                                FileUtils.copyFile(destination, currentDB);

                                Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.successful_importing_db), Snackbar.LENGTH_LONG).show();
                            } catch (IOException e) {
                                Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.error_in_importing_db), Snackbar.LENGTH_LONG).show();
                            }

【问题讨论】:

    标签: android sqlite android-studio file google-drive-api


    【解决方案1】:

    在与 targetsdk 和不同的文件方法苦苦挣扎之后,我在 youtube 上看到了一个视频,并让我想到了使用 contextWrapper 类,我能够解决这个问题。这是我写的新代码:

    ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
            File currentDB = contextWrapper.getDatabasePath(Constants.dataBaseName);
    
            File destinationDirectory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
            File destination = new File(destinationDirectory, Constants.dataBaseName + ".db");
    try {
                                    FileUtils.copyFile(destination, currentDB);
                                    Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.successful_importing_db), Snackbar.LENGTH_LONG).show();
                                } catch (IOException e) {
                                    Snackbar.make(findViewById(R.id.activity_backup_restore), getString(R.string.error_in_importing_db), Snackbar.LENGTH_LONG).show();
                                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      相关资源
      最近更新 更多