安卓:数据库导出工作在模拟器,而不是手机 [英] Android: database export works on emulator, not on phone

查看:169
本文介绍了安卓:数据库导出工作在模拟器,而不是手机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的应用程序的数据库导出到SD卡。它的工作原理优秀的仿真器,车针不是我的电话。

I'm trying to export my application's database to SDcard. It works excellent for emulator, bur not for my phone.

    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()在手机上返回假的,但我检查了文件 - 它的存在。
什么是错我的电话?

This currentDB.exists() returns false on the phone, but I checked the file - it exists. What is wrong with my phone?

推荐答案

您提供文件错误的参数。从Android的文档:

You are supplying File wrong parameters. From Android doc:

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

在您的code:

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

这可能是这样的:

It could be like this:

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);
    /* ... */

我很惊讶这个工作在模拟器,我对此表示怀疑。它可能会创建一个空文件,原因至少这行做某种感觉,虽然你的变量是不是你叫他们:

It surprises me this works on emulator, I doubt that. It probably creates an empty file becuase at least this line makes some sort of sense, although your variables are not what you named them:

File backupDB = new File(sd, backupDBPath);

另外,你或许应该创建一个最后块,并做有一些 FileChannel 清理。

这篇关于安卓:数据库导出工作在模拟器,而不是手机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆