【问题标题】:How to make database backup in SDcard如何在 SD 卡中进行数据库备份
【发布时间】:2016-06-10 16:56:29
【问题描述】:

我已经成功备份了我的数据库,但问题是我的备份保存在内存中而不是 SD 卡中。

这是我的代码:

public void exportDatabase()
{
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    String currentDBPath = "/data/" + "com.arpanexample.spm" + "/databases/" + Database.DATABASE_NAME;
    String backupDBPath = Database.DATABASE_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        FileChannel source = new FileInputStream(currentDB).getChannel();
        FileChannel destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(context, "Successfully backup your data", Toast.LENGTH_LONG).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

    标签: android android-database


    【解决方案1】:

    默认情况下,Context 类/SQLiteOpenHelper 类不允许您将数据库文件保存在内部应用程序存储之外的任何其他位置。即 /data/data/com.you.packagename/databases。您确实获得了一个用于处理 SQLite 数据库的自定义类或推出您的 - 获取 Android Sources 目录中的 SQLiteOpenHelper 类,如果您知道自己在做什么,请对其进行编辑。这是一个自定义implementation of SQLiteOpenHelper you can use.

    【讨论】:

      【解决方案2】:

      我想尝试类似的东西,但没有找到合适的教程。

      后来,使用 FileCache 将内容保存在 SD 卡中。 缓存将有助于连接到互联网的应用程序。

      package com.sumukh.myApp.anotherjsonparser;
      
      import java.io.File;
      
      import android.content.Context;
      
      public class FileCache {
      
      private File cacheDir;
      
      public FileCache(Context context) {
          // Find the dir to save cached images
          if (android.os.Environment.getExternalStorageState().equals(
                  android.os.Environment.MEDIA_MOUNTED))
              cacheDir = new File(
                      android.os.Environment.getExternalStorageDirectory(),
                      "AppCache");
          else
              cacheDir = context.getCacheDir();
          if (!cacheDir.exists())
              cacheDir.mkdirs();
      }
      
      public File getFile(String url) {
          String filename = String.valueOf(url.hashCode());
          // String filename = URLEncoder.encode(url);
          File f = new File(cacheDir, filename);
          return f;
      
      }
      
      public void clear() {
          File[] files = cacheDir.listFiles();
          if (files == null)
              return;
          for (File f : files)
              f.delete();
         }
      
      }
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2011-01-11
        • 1970-01-01
        • 2011-01-01
        • 2019-09-21
        • 2012-06-07
        • 1970-01-01
        • 2019-09-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多