Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import an existing SQLite table into Android Room?

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.

like image 460
vimerate Avatar asked Nov 14 '17 16:11

vimerate


People also ask

What is the difference between SQLite and room database in Android?

Realm is an easy-to-use, open-source alternative to SQLite. The key difference between the two is that Realm is an object database management system, while SQLite is a relational database management system.


1 Answers

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

}

in my case i initialize room as a dependency using dagger

like image 140
alireza rahmaty Avatar answered Oct 18 '22 18:10

alireza rahmaty