【问题标题】:How to import an existing SQLite table into Android Room?如何将现有的 SQLite 表导入 Android Room?
【发布时间】:2017-11-14 16:41:20
【问题描述】:

我正在开发一个琐事应用程序,并且我已经在应用程序中实现了 Room Persistence,但是我无法找到可以从应用程序随附的 SQLite db 文件中导入现有表的信息。

【问题讨论】:

  • “将 db 文件导入应用程序”究竟是什么意思?
  • 资产文件----?
  • 我的意思是将数据导入到 Room 表中。
  • Room 上的每个文档都显示它被用于创建数据库。但是假设我们在custom/path/database.db 有一个现有的 SQLite 数据库。我们如何将内存中的类映射到该位置?

标签: android android-room


【解决方案1】:

这似乎有点晚了,但我通过这个解决方案解决了这个问题。 在初始化房间数据库之前,您需要将现有的 sqlite db 文件复制到 /data/data/{your package name}/databases 目录

您可以使用此方法复制文件

   public static void copyDataBase(Context context, String dbName) throws IOException {

    InputStream myInput = context.getAssets().open(dbName); 
    String outFileName =  "/data/data/"
            +context.getApplicationContext().getPackageName()
            + "/databases/" + dbName;
    File file=new File(outFileName);
    if (file.exists())
        return; 
    OutputStream myOutput = new FileOutputStream(outFileName); 
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);

    } 
    myOutput.flush();
    myOutput.close();
    myInput.close();
}

然后在您的应用程序类中执行以下操作:

public class ErrorReporterInit extends Application  {

public static ApplicationComponent applicationComponent;

@Inject
DispatchingAndroidInjector<Activity> activityDispatchingAndroidInjector; 

@Override
public void onCreate() {
    super.onCreate();

    try {
        GeneralUtil.copyDataBase(this,"{your existing db file in asset}");
    } catch (IOException e) {
        e.printStackTrace();
    }

    applicationComponent = DaggerApplicationComponent.builder()
            .application(this).build();
    applicationComponent.inject(this);

}



@Override
public void onTerminate() {
    super.onTerminate();
}

}

在我的例子中,我使用匕首将房间初始化为依赖项

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多