Search code examples
androiddatabasesqlitesqliteopenhelper

Do you have to alter the database schema in the onUpgrade method of the SQLiteOpenHelper?


I'm trying to write an android app that contains a database that would dynamically change its schema based on user input.

For example, suppose that you initially have a table in which the only column is a column for different breeds of puppies. This would be the primary key. The user can then dynamically add new attributes which would correspond to new columns in this table (e.g. color, has spots, size, etc.)

I was wondering whether the ALTER TABLE query must be executed in onUpgrade or whether I can do it in another method within the SQLiteOpenHelper subclass. I don't really know if it is really necessary to increment the database version every time the user wants to add a new attribute. Thanks!


Solution

  • I was wondering whether the ALTER TABLE query must be executed in onUpgrade or whether I can do it in another method within the SQLiteOpenHelper subclass.

    You are welcome to execute ALTER TABLE statements whenever you want, though (as with all database I/O) on a background thread, please.

    In your case, I do not know why you are using SQLiteOpenHelper, though. The point behind SQLiteOpenHelper is to help developers building apps with fixed (per version) schemas. That is not the route that you are taking, in which case SQLiteOpenHelper may not really be helping much.