如何将现有数据库从一个应用程序复制到另一个

时间:2011-04-14 10:56:58

标签: android database

我一直在创建第一个应用的付费版本。

我想将现有数据库复制到新的付费应用程序。

这怎么可能?

修改

在免费应用中,我使用SQLiteOpenHelper。他们可以使用相同的数据库,但又想再次使用SQLiteOpenHelper,并且无法弄清楚如何使用其他数据库,因为应用程序具有不同的包名称(如果他们使用相同的dos不当应用程序被删除时,免费数据库会被删除吗?)。

如果您想了解更多信息(以及您可能需要的信息,请发表评论))

1 个答案:

答案 0 :(得分:6)

您有几个选项,您将无法获得具有不同名称的包以直接与另一个包数据库进行交互。

  • 因此,您可以将Content Provider编码到免费应用中,然后允许付费版本从内容提供商处收集数据,然后在首次运行时传递所有数据。这在我看来有点麻烦 - 但是意味着用户不需要SD卡,你也可以控制数据,IE如果用户已经使用了付费版本,你可以将数据添加到数据库而不是替换新旧的免费赠送......

  • 您可以从免费版本中将数据库保存到SD卡,然后使用付费版本收集它。根据您要编码的数量,您可以在免费应用中设置Broadcast Receiver,然后在付费版本中设置sendBroadcast(),这样当免费应用收到广播时,它会将其数据库应对到SD卡,然后付费应用程序收集它。另一种方式是用户单击免费版本中的保存按钮,备份到SD卡,然后用户单击付费版本中的按钮并接收它 - 这可以像复制文件一样简单并替换应用程序的数据库,或者您可以将其作为不同的数据库导入付费应用程序,处理它将您需要的内容添加到主数据库然后丢弃它。

作为一个非常松散和简单的指针,你可以用这样的东西将数据库复制到SD卡,它从代码的工作位被剥离,因此应该被认为是未经测试的程度 - 你需要添加在一些地方捕获一些块以使其与清单中SD卡的读写权限一起工作:

    // Get hold of the db:
    InputStream myInput = new FileInputStream("/data/data/com.package.name/databases/database-name");
    // Set the output folder on the SDcard
    File directory = new File("/sdcard/someFolderName");
    // Create the folder if it doesn't exist:
    if (!directory.exists()) 
    {
        directory.mkdirs();
    }     
    // Set the output file stream up:
    OutputStream myOutput = new FileOutputStream(directory.getPath()+ "/database-name.backup");
    // Transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0)
    {
        myOutput.write(buffer, 0, length);
    }
    // Close and clear the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

Retreival非常相似:

    // Set location for the db:
    OutputStream myOutput = new FileOutputStream("/data/data/com.package.name/databases/database-name");
    // Set the folder on the SDcard
    File directory = new File("/sdcard/someFolderName");
    // Set the input file stream up:
    InputStream myInput = new FileInputStream(directory.getPath()+ "/database-name.backup");
    // Transfer bytes from the input file to the output file
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer))>0)
    {
        myOutput.write(buffer, 0, length);
    }
    // Close and clear the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

但是我建议先做一些检查并稍微询问用户:

  • 检查SD卡上是否已存在文件,如果是,则要覆盖它。
  • 检查他们是否要使用备份数据覆盖当前数据库
  • 您还需要进行一些检查,例如,是否已安装SD卡等。

就像我说上面的代码只是为了给你一些关于如何使用SD卡移动数据库的提示。