2

Hi I am developing Android application in which I am using active android. I tried to add one column to my table by using migration. I tried with following code:

ALTER TABLE TAGS ADD COLUMN TAG_DATE INTEGER;

Its working fine on current version. But I have two older versions of my application. One A has TAG table already and other one B not having TAG table. So when I tried to update from A to current version then its working fine. But when I tried from B to current version in that case it first creates TAG table with TAG model class which has TAG_DATE column in this case it gives me duplicate column error while executing this script. So what I want to do I want check if column already exists or not. If not then Alter and add column.

Is there any way to do this in active-android scripts. Need some help. Thank you.

nilkash
  • 7,408
  • 32
  • 99
  • 176

1 Answers1

2

In your onCreate Application.class

ActiveAndroid.initialize(this);
DBHelper.createIfNeedColumn(YOUR_ORM_CLASS, COLUMN_KEY);

And DBHelper.class static class

public static boolean createIfNeedColumn(Class<? extends Model> type, String column) {
    boolean isFound = false;
    TableInfo tableInfo = new TableInfo(type);

    Collection<Field> columns = tableInfo.getFields();
    for (Field f : columns) {
        if (column.equals(f.getName())) {
            isFound = true;
            break;
        }
    }
    if (!isFound) {
        ActiveAndroid.execSQL("ALTER TABLE " + tableInfo.getTableName() + " ADD COLUMN " + column + " TEXT;");
    }
    return isFound;
}
kutukoff
  • 43
  • 6
  • It didn't work for me.it adds the column; when I check the database in a DB Browser I see that the new column does exist but your code always return false even after adding the table! any solution? – Amin Aug 04 '20 at 11:40