0

I don't know very much about SQLite so, i want to know what is use of onCreate() and onUpgrade() method of SQLiteOpenHelper.

And when the onCreate() and onUpgrade() method is called.?

akhil batlawala
  • 1,066
  • 1
  • 10
  • 30
  • If you want to ask a new question, you should ask a new question instead of editing an old, closed question. Also, your new question regarding "please recommend me a database library to use for Android applications" would be closed as off-topic, so don't actually ask the question. – EpicPandaForce Aug 24 '16 at 13:23

2 Answers2

0

Documentation

SQLiteOpenHelper onCreate() and onUpgrade() callbacks are invoked when the database is actually opened, for example by a call to getWritableDatabase(). The database is not opened when the database helper object itself is created.

SQLiteOpenHelper versions the database files. The version number is the int argument passed to the constructor. In the database file, the version number is stored in PRAGMA user_version.

onCreate() is only run when the database file did not exist and was just created. If onCreate() returns successfully (doesn't throw an exception), the database is assumed to be created with the requested version number. As an implication, you should not catch SQLExceptions in onCreate() yourself.

onUpgrade() is only called when the database file exists but the stored version number is lower than requested in constructor. The onUpgrade() should update the table schema to the requested version.

When changing the table schema in code (onCreate()), you should make sure the database is updated. Two main approaches:

  1. Delete the old database file so that onCreate() is run again. This is often preferred at development time where you have control over the installed versions and data loss is not an issue. Some ways to to delete the database file:

    • Uninstall the application. Use the application manager or adb uninstall your.package.name from shell.

    • Clear application data. Use the application manager.

  2. Increment the database version so that onUpgrade() is invoked. This is slightly more complicated as more code is needed.

    • For development time schema upgrades where data loss is not an issue, you can just use execSQL("DROP TABLE IF EXISTS <tablename>") in to remove your existing tables and call onCreate() to recreate the database.

    • For released versions, you should implement data migration in onUpgrade() so your users don't lose their data.

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
Yogesh Rathi
  • 6,331
  • 4
  • 51
  • 81
0

onUpgrade() is called (you do not call it yourself) when version of your DB is changed which means underlying table structure changed etc.

oncreate(): called only once when database is created for the first time. It's used to create a table in a database.

Laurel
  • 5,965
  • 14
  • 31
  • 57
MurugananthamS
  • 2,395
  • 4
  • 20
  • 49