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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With