0

I have encounter some difficulties saving my data after i added new column to my sqlite. e.g the column_contact_grp in the example below

in my contract class:

 public final static String _ID = BaseColumns._ID;
    public final static String COLUMN_CONTACT_NAME = "name";
    public final static String COLUMN_CONTACT_NUMBER = "number";
    public final static String COLUMN_CONTACT_GRP = "group";

in my Dbhelper class:

 @Override
public void onCreate(SQLiteDatabase db) {
    // Create a String that contains the SQL statement to create the pets table
    String SQL_CREATE_CONTACTS_TABLE = "CREATE TABLE " + NameEntry.TABLE_NAME + " ("
            + NameEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + NameEntry.COLUMN_CONTACT_NAME + " TEXT NOT NULL, "
            + NameEntry.COLUMN_CONTACT_NUMBER + " TEXT,"
            + NameEntry.COLUMN_CONTACT_GRP + " TEXT );";

    // Execute the SQL statement
    db.execSQL(SQL_CREATE_CONTACTS_TABLE);
}

in my Main Activity:

ContentValues values = new ContentValues();
    values.put(NameEntry.COLUMN_CONTACT_NAME, "Name");
    values.put(NameEntry.COLUMN_CONTACT_NUMBER, "1234");
    values.put(NameEntry.COLUMN_CONTACT_GRP, "testing");

The program "used to work and save well" but it fail saving when i added a new data. When i remove the additional code (COLUMN_CONTACT_GRP related codes), it will work again, able to save and display name and number correctly on my listview. Anyone can guide where should i look out for the errors?

Dhanumjay
  • 540
  • 7
  • 17
East
  • 17
  • 1

3 Answers3

2

word "group" is SQLite keywords, use another keyword, check this link

Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
2

You should use onUpgrade Method .

Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.

Example

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 1) { // Add your Version .
         db.execSQL(DATABASE_ALTER);
    }

}


 private static final String DATABASE_ALTER = "ALTER TABLE "
    + TABLE_NAME + " ADD COLUMN " + COLUMN_ONE + " string;";
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

Increase your DataBase Version and in onUpgrade method write to query to add a column in the table.

Shailendra Yadav
  • 1,822
  • 1
  • 12
  • 16