【问题标题】:How to export and import database sqlite in android studio?如何在android studio中导出和导入数据库sqlite?
【发布时间】:2017-02-08 15:41:30
【问题描述】:

我正在尝试在我的 android 应用程序中实现导出和导入,我尝试了以下导出方法,但它不起作用并且没有给出任何错误。谁能帮帮我。

public static void export() throws IOException {
    //Open your local db as the input stream
    String inFileName = "/data/data/com.example.main/databases/myDB";
    File dbFile = new File(inFileName);
    FileInputStream fis = new FileInputStream(dbFile);

    String outFileName = Environment.getExternalStorageDirectory()+"/myDB";
    //Open the empty db as the output stream
    OutputStream output = new FileOutputStream(outFileName);
    //transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = fis.read(buffer))>0){
        output.write(buffer, 0, length);
    }
    //Close the streams
    output.flush();
    output.close();
    fis.close();
}

我这样调用方法:

try {
    export();
}
catch (IOException e) {
    e.printStackTrace();
}

我做错了什么?并且一旦导出,我该如何导入数据?

【问题讨论】:

  • 详细解释“它不起作用”是什么意思。
  • 我不确定到底是什么不工作,数据没有被导出。我在单击按钮时使用 export() 方法,所以当我按下按钮时什么都没有发生。如果我在没有提出的方法中有 Log.d。
  • 你从哪里得到的代码?你听得懂么?您是否在日志中获得堆栈跟踪?
  • 我没有得到堆栈跟踪。
  • 您确定这就是您导出数据库的方式吗?您能否检查您正在使用FileInputStream 阅读的文件是否可以通过这种方式导出?在我看来,您需要通过某种方式与 SQL 进行通信才能提出此要求。

标签: java android sqlite android-studio export


【解决方案1】:

我相信您所需要的在这里得到了回答......它对我有用..

copy database file to sdcard in android

注意:这并不是一个懒惰的答案,简单地说,我知道这很有效,所以希望它可以帮助发帖者!

【讨论】:

  • 这也不行,我知道两个代码都是正确的,可能还有其他问题吗?我正在调用方法 write 但不确定它们是否正在执行,因为日志没有打印,你能否给我一些关于你如何让它工作的指针?
  • 嗨 Adam,对我来说,我在特定的 Utilities 类中创建了一个静态函数,然后调用了它。我另外做的是确保清单包含 android.permission.WRITE_EXTERNAL_STORAGE。你有没有机会错过它?
  • 感谢您回来。我已经在清单中声明了权限。
  • Adam,您是否尝试在代码运行时单步执行?我想知道当应用程序逐步执行上述代码时,您的路径等是否都正确?
  • 我对android还很陌生,你能告诉我如何单步执行代码吗?我知道我的 inFileName 目录是正确的,因为我已经使用该命令完成了它。我不确定如何访问我的数据库,因为 adnroid 监视器没有显示我的手机。
猜你喜欢
  • 1970-01-01
  • 2013-05-08
  • 2019-11-12
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
相关资源
最近更新 更多