android - When is SQLiteOpenHelper onCreate() / onUpgrade() run? -


i create tables in sqliteopenhelper oncreate() receive

sqliteexception: no such table 

or

sqliteexception: no such column 

errors. why?

note:

(this amalgamated summary of tens of similar questions every week. attempting provide "canonical" community wiki question/answer here questions can directed reference.)

sqliteopenhelper oncreate() , onupgrade() callbacks invoked when database opened, example call getwritabledatabase(). database not opened when database helper object created.

sqliteopenhelper versions database files. version number int argument passed constructor. in database file, version number stored in pragma user_version.

oncreate() run when database file did not exist , created. if oncreate() returns (doesn't throw exception), database assumed created requested version number. implication, should not catch sqlexceptions in oncreate() yourself.

onupgrade() called when database file exists stored version number lower requested in constructor. onupgrade() should update table schema requested version.

when changing table schema in code (oncreate()), should make sure database updated. 2 main approaches:

  1. delete old database file oncreate() run again. preferred @ development time have control on installed versions , data loss not issue. ways to delete database file:

    • uninstall application. use application manager or adb uninstall your.package.name shell.

    • clear application data. use application manager.

  2. increment database version onupgrade() invoked. more complicated more code needed.

    • for development time schema upgrades data loss not issue, can use execsql("drop table if exists <tablename>") in remove existing tables , call oncreate() recreate database.

    • for released versions, should implement data migration in onupgrade() users don't lose data.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

java.lang.NoClassDefFoundError When Creating New Android Project -

Decoding a Python 2 `tempfile` with python-future -