Search code examples
androidsqliteconventions

Conventions to insert default values into SQLite Database in Android


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.


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