Android:数据库导出适用于模拟器,不适用于手机

标签 android database export

我正在尝试将我的应用程序的数据库导出到 SD 卡。它非常适合模拟器,但不适用于我的手机。

    OnClickListener mExportListener = new OnClickListener(){
public void onClick(View v){
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();
        if (sd.canWrite()) {
            String currentDBPath = "\\data\\com.mypck.myapp\\databases\\database";
            String backupDBPath = "database.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();
            }else{
             String msg = activity.getResources().getString(R.string.something_wrong);        
             Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);  
             toast.show();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
};

currentDB.exists() 在手机上返回 false,但我检查了文件 - 它存在。 我的手机出了什么问题?

最佳答案

您提供的 File 参数有误。来自 Android 文档:

File(String parent, String child) 
    parent - The parent pathname string
    child - The child pathname string 

在你的代码中:

parent => \\data  
child => \\data\\com.mypck.myapp\\databases\\database  
resulting path => \\data\\data\\com.mypck.myapp\\databases\\database => wrong

可能是这样的:

String sd = Environment.getExternalStorageDirectory();
if (sd.canWrite()) {
    String currentDBPath = "data/data/com.mypck.myapp/databases/your_database_name.db";
    String backupDBPath = sd + "/your_output_file_name.db";
    File currentDB = new File(currentDBPath);
    File backupDB = new File(backupDBPath);
    /* ... */

令我惊讶的是这在模拟器上有效,我对此表示怀疑。它可能会创建一个空文件,因为至少这一行有某种意义,尽管您的变量不是您命名的:

File backupDB = new File(sd, backupDBPath);

您还应该创建一个 finally block 并在其中做一些 FileChannel 清理工作。

关于Android:数据库导出适用于模拟器,不适用于手机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8166920/

相关文章:

php - 哪些数据库支持加密

linux - 如何从 DVD 驱动器运行 1 .sh,从硬盘运行 2nd .sh?

r - 如何将多个表、数据框、回归结果等写入一个 Excel 文件?

linux - 如何在 Linux 中从文件运行 Bash 'export' 命令?

Android TV - SearchBar 焦点

textview中的android闪烁字符

php - mysql_query如何与一个 "dynamic"数据库一起使用呢?

sql - 从 SELECT 语句更新列

android - 如何使用 Room Db 返回 Rx Single 交易?

android - Fragments - 指定的 child 已经有一个 parent 。您必须先在 child 的 parent 上调用 removeView()