Search code examples
androidperformancesqlitesqliteopenhelper

Setting initial values for SQLite in onCreate() of SQLiteOpenHelper


I am creating an Android app for which I need to create a SQLite DB and pre-populate it with some values.

The Android documentation says this about what to do in "onCreate" of the SQLiteOpenHelper:

Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.

Reference - http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#onCreate(android.database.sqlite.SQLiteDatabase)

I am doubtful about the following 2 things -

  • What is meant by "when database is created for the first time"? Is this done on the first launch of the app or only when the first DB request (read/write etc) is done.

    If it is the latter, I fear that it may take quite some time to create DB, pre-populate it with values (I have about 60 rows to be inserted into 1 table) and then read the DB to show it. Is this the best practice?

  • I have been doing all my DB operations in AsyncTasks. But I am doing the table creations in onCreate using "db.execSQL" statements. Is this fine (in terms of convention/ performance) or should I go for an AsyncTask here as well?

Any help is appreciated.


Solution

  • What is meant by "when database is created for the first time"? Is this done on the first launch of the app or only when the first DB request (read/write etc) is done.

    • It happens when you first query from database in general term. After that only Upgrade method is called that too when you change the db version.

    If it is the latter, I fear that it may take quite some time to create DB, pre-populate it with values (I have about 60 rows to be inserted into 1 table) and then read the DB to show it. Is this the best practice?

    • 60 rows insertion is not a big task. More you can read about beginTransaction(),commitTransaction and endTransaction for insertion. It will make your insertion task lighting fast.

    I have been doing all my DB operations in AsyncTasks. But I am doing the table creations in onCreate using "db.execSQL" statements. Is this fine (in terms of convention/ performance) or should I go for an AsyncTask here as well?

    • It good you are doing you Db operation in AsyncTask and its completely fine.