2012-07-30 40 views
0

我的问题是,我想恢复我的应用程序的sqlite数据库后,我覆盖我的设备上的同一个应用程序。我不喜欢在启动我的应用程序时反复添加设置。保存sqlite数据库android应用覆盖后

那么有可能在android中将数据库保存在某个地方,我可以从中恢复它?

我已经在Google和SO上搜索了超过几个小时,但无法找到任何解决方案。

编辑:它不是一个固定的数据库。所以我不能将它存储在资产文件夹中。它可以由用户编辑,但默认情况下它应该包含最后编辑的值(覆盖应用程序之前的值)。

+0

问题不是很清楚。更新应用程序时,数据库不会被删除,所以我不明白为什么您需要从某处进行恢复。 – Kuffs 2012-07-30 12:45:40

+0

如果您只是使用相同的密钥更新您的应用程序进行签名,数据库应该仍然存在,afaik。在覆盖onUpdate()清除数据库之后打开数据库时可能会出现这种情况。 - 只是一个想法,可能是错误的... – Martze 2012-07-30 12:45:45

+0

@ Kuffs-我完全删除了我的应用程序广告,然后再次安装..因此我每次都丢失了我的sqlite数据库..我需要恢复它。 – 2012-07-30 12:47:51

回答

1

这种方法,我觉得非常有帮助:

public static void movedb(File srcdb, File destdb) 
{ 
    try 
    { 
     if (Environment.getExternalStorageDirectory().canWrite()) 
     {     
      if (srcdb.exists()) 
      { 
       FileChannel src = new FileInputStream(srcdb).getChannel(); 
       FileChannel dst = new FileOutputStream(destdb).getChannel(); 
       dst.transferFrom(src, 0, src.size()); 
       src.close(); 
       dst.close();      
      } 
      else 
      { 
       //ERROR: "Database file references are incorrect"      
      } 
     } 
     else 
     { 
      //ERROR: "Cannot write to file" 
     } 
    } 
    catch (Exception e) 
    { 
     //ERROR: e.getMessage() 
    } 
} 

然后我打电话

movedb(this, new File(<context>.getDatabasePath("...your DB name...")), new File("... your location ...")); 

要备份,然后恢复:

movedb(this, new File("... your location ..."), new File(<context>.getDatabasePath("...your DB name..."))); 
+0

但我想知道如果我卸载我的应用程序,我将如何拥有srcdb文件?我对此没有确切的想法。感谢您的回复。 – 2012-07-30 13:06:38

+0

在卸载之前,可以使用此代码复制数据库(位于外部存储目录中的文件中)。然后当你重新安装时,你可以恢复数据库。 – 2012-07-30 13:12:44

+0

数据获取存储在SD卡上。对 ?? – 2012-07-30 13:14:48

0

我使用ORMLite除了将数据库存储在外部公共目录之外,在将文件还原到数据库目录后,我必须重新实例化DatabaseHelper单例并创建一个新单例。

这里是我的版本,省略每个try/catch块用于simplicitiy的缘故:

public boolean restoreBackup(Context context){ 

    String databasePath = "data/data/my.package.name/databases/myDatabase.sqlite"; 
    String backUpPath = context.getDatabaseDir("myDatabase.sqlite"); 

    // Copies back-up to database directory 
    new File(databasePath).delete(); 
    FileInputStream streemToBackUp = new FileInputStream(new File(backUpPath)); 
    OutputStream streamToDatabaseFile = new FileOutputStream(databasePath); 

    byte[] buffer = new byte[1024]; 
    int length; 
    while ((length = streamToBackUp.read(buffer)) > 0) { 
     streamToDatabaseFile.write(buffer, 0, length); 
    } 
    streamToDatabaseFile.flush(); 
    streamToDatabaseFile.close(); 
    streamToBackUp.close(); 

    // Re-instantiate DatabasHelper singleton 
    DatabaseHelper.closeHelper(); 
} 

closeHelper()身体如下:

public static void closeHelper() { 
    helper.close(); 
} 

@Override 
public void close() { 
    super.close(); 
    myDao = null; // Set to null every day you have 
    helper = null; // Set to null the singleton instance of the helper 
} 

这将工作,只要你不要使用 OpenHelperManager类来实例化助手,并且在需要数据库时总是使用getHelper()而不是存储返回的实例。