I want to insert required data for my application at the beginning and I will use these data. And I want to insert once, and there must be no duplicate. Therefore, in “onCreate”, I’m doing like that : if the row count of table(such as student etc) is 0, I’m inserting students. I don’t think it’s the best way to do this. Therefore I want to learn if there is a better way.
Share
If you want your database populated at install time and never any other time, your only reasonable option is to package your pre-populated database with your APK as a built-in resource. This has the advantage of simplifying your app.
Alternately, if you implement the
SQLiteOpenHelperfor your database, anything you insert duringSQLiteOpenHelper.onCreate(SQLiteDatabase)will only ever be inserted either on the first run of you app or when someone clears all your app’s data (which is more or less putting you back to a fresh install anyway). TheSQLiteOpenHelpersuperclass knows whether or not to run the creation code when you call one of thegetWritableDatabase()orgetReadOnlyDatabase()methods to get your database reference.It is worth noting that Android doesn’t really let you run an installer the way desktop software does. If you need to do any setup work, you need to be able to detect and remember when your app has been run before.