如何将现有的SQLite表导入Android Room?

vim*_*ate 5 android android-room

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

ali*_*aty 2

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

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

   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();
}
Run Code Online (Sandbox Code Playgroud)

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

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();
}

}
Run Code Online (Sandbox Code Playgroud)

就我而言,我使用 dagger 将 room 初始化为依赖项