There are basically 2 approaches:
-
Setting a .db file and copying the file
-
Setting a function to populate it and then assigning a value at SharedPreferences that holds the state (preferred).
- A valid .db
An Android database will need to have at least (and firstly) a android_metadata table and then the tables that your app requires with the first column being the base ID for Android (_id).
(check the appendix if not knowing how to populate a db using sqlite3)
e.g:
CREATE TABLE android_metadata(
locale TEXT DEFAULT 'en_US'
);
CREATE TABLE table_name(
_id INTEGER PRIMARY KEY,
myfield TEXT NOT NULL DEFAULT 'default'
);
Now we need to set our base class and methods to run on the first initialization. It will be like this: DbPrebuilt.java
Then, at the initialization:
DbPrebuilt db = new DbPrebuilt(Splash.this);
try {
db.createDatabase();
} catch (IOException e) {
e.printStackTrace();
}
There's not a single difficulty here. You'll just need to set up a SQLiteOpenHelper just as always and set up the code for populating it.
When first initializing your code:
- Verify if there is a value with TRUE for "initialized_db" value at your SharedPreferences
if (!mySharedPreferences.getBoolean('initialized_db')){
myFunctionToPopulateTheDatabase();
}
All of the code that runs to set a database is preferred to run in the brackground. Take a Service for that.
create the database schema
-- $ sqlite3 my_db_schema.db
CREATE TABLE table_name(
_id INTEGER PRIMARY KEY,
my_value TEXT NOT NULL
);
create the populater code
-- vim populate_db.sql
BEGIN TRANSACTION;
INSERT INTO table_name(my_value) VALUES('lol');
INSERT INTO table_name(my_value) VALUES('lol');
INSERT INTO table_name(my_value) VALUES('lol');
INSERT INTO table_name(my_value) VALUES('lol');
INSERT INTO table_name(my_value) VALUES('lol');
COMMIT TRANSACTION;
-- select count(my_value) from table_name
-- 5
run the code against the .db
$ sqlite3 my_db_schema.db < populate_db.sql