1

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!

Nick
  • 13
  • 2

2 Answers2

0

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

onUpgrade will only be called when the database file already exists but the stored user version is lower than requested in constructor. I have used this function to carry out the changes I made to the database schema when I release a new version of the app. But if you want to add columns dynamically, yes you can use the ALTER TABLE command.

Christian Abella
  • 5,747
  • 2
  • 30
  • 42