'Android SQLite same DB [duplicate]
I am using local DB (SQLite) with my android app. I know, that with every first launch of the app, a new database is created. Is there an easy and quick way to fetch the new database with my prepared data? I already have the database file ready.
Thank you for your help.
Solution 1:[1]
If you are using Room (and why wouldn't you?) it has the facility to pre-populate the database.
Room.databaseBuilder(appContext, AppDatabase.class, "Sample.db")
.createFromAsset("database/myapp.db")
.build()
https://developer.android.com/training/data-storage/room/prepopulate
Solution 2:[2]
You can use SQLiteAssetHelper, in short you copy the database to the assets/databases folder and SQLiteAssetHelper does the copy of the database from the package to the device the App is being installed on.
see Reading a database from the assets folder
If you are a little wary of SQLiteAssetHelper no longer being maintained then the following (The Recommended Fix) has an equivalent that uses the standard SQLiteOpenHelper.
see A pre-populated database does not work at API 28 throws "no such table" exception
Although Room (an objected orientated abstract layer over SQLite) has the createFromAsset
and createFromFile
. The issue is that Room has expectations of the database schema which would involve, unless you are very lucky, understanding the nuances/restrictions imposed by Room and very likely needing to convert the existing schema to suit Room
e.g. column types MUST be TEXT, REAL, BLOB or INTEGER nothing else, irrespective of SQLite's highly flexible column types that allow virtually any type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ivan Wooll |
Solution 2 |