I have one problem with Android SQLite
database.
I have one table which contains one field.StudentFname and that application is working fine with Android 2.3.1 and now if I add another field then my application is not working properly.
Can anyone help me who knows database very well,
I think we should not check condition like that
because if we use this , it means every time when we increase the database version then onUpdrade() will call and condition will be true , so we should check like that
so in this case if old version is 2 then condition will be false and user with old version 2 will not update the database(which user wants only for version 1), because for those users database had already updated .
To add a new column to the table you need to use
ALTER
. In android you can add the new column inside theonUpgrade()
.You may be wonder, how
onUpgrade()
will add the new column?When you implementing a subclass of
SQLiteOpenHelper
, you need to call superclass constructor:super(context, DB_NAME, null, 1);
in your class constructor. There I have passed1
for version.When I changed the version
1
to above(2
or greater),onUpgrade()
will invoked. And perform the SQL modifications which I intend to do. My class constructor after changed the version:SQL modifications checks like this, superclass constructor compares the version of the stored SQLite db file with the version that I passed to
super()
. If these(previous and now) version numbers are differentonUpgrade()
gets invoked.Code should look like this:
I came across this thread when needing help on my own app, but saw issues with many of the answers. I would recommend doing the following:
You want to make sure the code will work when users upgrade more than 1 version and that the update statement only runs the one upgrade it is needed. For a bit more on this, check out this blog.
I have done the following approach, it is resovled for me
if DB version : 6
When you upgrade to : 7 ( I am adding 1 new column in the 3 tables)
Where : "DATABASE_ALTER_ADD_PAPER_PAID" is query.
After above two operation it will works fine for the fresh install user and app upgrade user
The easiest way to do this is to add some
SQL to the onUpgrade()
method in yourSQLiteOpenHelper class
. Something like:you can use
ALTER TABLE
function on youronUpgrade()
method, like this:Obviously, the SQLite will differ depending on the column definition.