如何将现有的SQLite表导入Android Room? [英] How to import an existing SQLite table into Android Room?

查看:349
本文介绍了如何将现有的SQLite表导入Android Room?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing a trivia app and I have finished implementing Room Persistence into the app, but I'm having trouble finding info where I can import an existing table from a SQLite db file that I'm shipping with the app.

推荐答案

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

It seems a little bit late but i solved this issue by this solution. you need to copy your existing sqlite db file to /data/data/{your package name}/databases directory before you initialize room databse

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

you can use this method to copy file

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

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

and then in your application class do this:

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

}

在我的情况下,我使用匕首将room初始化为依赖项

in my case i initialize room as a dependency using dagger

这篇关于如何将现有的SQLite表导入Android Room?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆