Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Last active January 3, 2016 17:59
Show Gist options
  • Save cirocosta/8498779 to your computer and use it in GitHub Desktop.
Save cirocosta/8498779 to your computer and use it in GitHub Desktop.
A walkthrough preloading data - Andriod

Preloading Data - Android

There are basically 2 approaches:

  1. Setting a .db file and copying the file

  2. Setting a function to populate it and then assigning a value at SharedPreferences that holds the state (preferred).

With a .db

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

Without a .db

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

Considerations

All of the code that runs to set a database is preferred to run in the brackground. Take a Service for that.

Appendix

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment