Question

I'm currently building an app which utilises the SQLite Database in Android, I understand that the tables are set up when overriding "onCreate" in my subclass of SQLiteOpenHelper.

However, I want the database to be created with a set of default information and was wondering where it was conventional to insert this? Should I be doing this with SQL in onCreate, or later on by checking a preference such as "onFirstRun" and using my Helper class to insert some values in an Activity somewhere?

Any helps/tips appreciates, cheers.

Was it helpful?

Solution

I usually add default data on the OnCreate of the class that extends SQLiteHelper like this, because its only does once (unless you uninstall the app) and it is quite clear and easy:

public class XXX extends SQLiteOpenHelper {
 String sqlCreate = "CREATE TABLE X (codigo INTEGER, nombre TEXT)";
 String sql ="Insert into X ....";
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(sqlCreate);
    db.execSQL(sql);
}

OTHER TIPS

It is better to insert default information in onCreate of SQLiteOpenHelper if you haven't released your app already to store. If already released do it in onUpgrade of SQLiteOpenHelper by making the necessary validations. This way all the code related to db stays together and you can manage the upgrade scenarios gracefully.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top