Android Pre-Populated Database [duplicate]
Here is an example of how to create and populate a database, you can just do this on the app install, this only creates one entry though so may be inefficient for what you want to do.
private static class settingsDatabaseHelper extends SQLiteOpenHelper{
//SQL String for creating the table required
private static final String CREATE_SETTINGS_TABLE
= "CREATE TABLE tbl_settings(" +
"_ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"VOIPUSERNAME TEXT," +
"VOIPAUTHID TEXT," +
"PASSWORD TEXT," +
"VOIPDISPLAYNAME TEXT," +
"SIPPROXYSERVER TEXT," +
"SIPREGISTRAR TEXT," +
"SIPREALM TEXT," +
"EXPIRESTIME INTEGER);";
//constructor
public settingsDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SETTINGS_TABLE);
ContentValues initialValues = new ContentValues();
initialValues.put("VOIPUSERNAME", "xxxxx");
initialValues.put("VOIPAUTHID", "xxxxxxxxxx");
initialValues.put("PASSWORD", "xxxxxx");
initialValues.put("VOIPDISPLAYNAME", "xxxxxxxxx");
initialValues.put("SIPPROXYSERVER", "xxxxxxxxxxxxx");
initialValues.put("SIPREGISTRAR", "xxxxxxxxxxx");
initialValues.put("SIPREALM", "xxxxxxxxxx");
initialValues.put("EXPIRESTIME", xxxxxxxxxxx);
Log.d("1.6", "gets to here");
db.insert(SETTINGS_TABLE, null, initialValues);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " +
newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SETTINGS_TABLE);
onCreate(db);
}
}
//end helper class
}
the way I'm going here is to ship a prepopulated database in the assets folder. You can drop in files there and use them as-they-are. Beware, however, that there is a size limit of 1MB, so maybe you'll have to split files, or compress them.
Compression is quite handy and well supported by the os itself.
hope this was of any help :-)
JavaDoc from SQLiteOpenHelper:
A helper class to manage database creation and version management. You create a subclass implementing onCreate(SQLiteDatabase), onUpgrade(SQLiteDatabase, int, int) and optionally onOpen(SQLiteDatabase), and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary. Transactions are used to make sure the database is always in a sensible state.
For an example, see the NotePadProvider class in the NotePad sample application, in the samples/ directory of the SDK.
So if you extend this class, you have 3 methods which will be called in some cases and you can choose, what do to. Thats the best practice :)