如何将SQLite数据库备份到SD卡?

问题描述 投票:0回答:1

如何将SQLite数据库备份到SD卡?我在这里看了很多例子,但没有一个适合我。我在清单中添加了以下行:

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

以及带有textview的片段,单击并执行备份:

    // Find the Text View that displays the Backup Database Button //
    TextView backupDatabaseTextView = (TextView) rootview.findViewById(R.id.backup_database_text_view);

    // Set a click listener on the backup database text view //
    backupDatabaseTextView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            exportDB();

        }
    });

以及以下方法:

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

        if (sd.canWrite()) {
            String currentDBPath = "//data//" + "com.budgettrackpro.android.budgettrackpro"
                    + "//databases//" + "budgettrackpro.db";
            String backupDBPath = "BudgetTrackPro";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            FileChannel src = new FileInputStream(currentDB).getChannel();
            FileChannel dst = new FileOutputStream(backupDB).getChannel();
            dst.transferFrom(src, 0, src.size());
            src.close();
            dst.close();
            Toast.makeText(getActivity(), "Backup Successful!",
                    Toast.LENGTH_SHORT).show();

        }
    } catch (Exception e) {

        Toast.makeText(getActivity(), "Backup Failed!", Toast.LENGTH_SHORT)
                .show();

    }
}
android sqlite
1个回答
0
投票

当我调试时,它找到了SD卡,但随后掉到了try catch的底部

我不知道如何解释,因为我不知道你认为代码中哪些代码“找到了SD卡”。例如,您的代码与可移动存储无关。

所以,这里有各种各样的问题,按照当前难度来源的可能性的降序排列(尽管你应该修复所有这些问题):

No Runtime Permission Support

您在Android 8.1上运行。从Android 6.0开始,你需要request certain permissions at runtime,而WRITE_EXTERNAL_STORAGE就是那些权限之一。

Hardcoded Database Path

String currentDBPath = "//data//" + "com.budgettrackpro.android.budgettrackpro"
                + "//databases//" + "budgettrackpro.db";

永远不要硬编码路径。替换为:

File currentDB = getActivity().getDatabasePath("budgettrackpro.db");

(并摆脱File currentDB = new File(data, currentDBPath);线,因为你将不再需要它)

Not Logging the Exception

在开发应用程序时,请记录所有异常。在Toast.makeText()区块的catch线上方添加此行:

Log.e(getClass().getSimpleName(), "Exception backing up database", e);

然后,use LogCat检查与任何崩溃相关的堆栈跟踪。

Doing I/O on the Main Application Thread

充其量,您的用户界面将在exportDB()通话期间被冻结,您的用户会认为您的应用已损坏。在最坏的情况下,你会崩溃,因为:

  • 备份花费的时间太长,占用主应用程序线程,或者
  • StrictMode抱怨主应用程序线程上的磁盘I / O.

请将此工作移至后台主题。

Not Making the Backup Visible to the User

即使你创建文件,the user will not be able to see that it exists没有重新启动或等待几个小时。

© www.soinside.com 2019 - 2024. All rights reserved.