Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upgrade sqlite table in android

I have table called person with 3 columns .They are ID,NAME and PASSWORD .I need to add new column called AGE.I try it this way but it doesn't work for me please help me to overcome this problem

public class Userdb {
    public static final String KEY_ROWID = "Id";
    public static final String KEY_NAME = "Person_name";
    public static final String KEY_PASSWORD = "Person_password";
    public static final String KEY_AGE = "Person_age";

    private static final String DATABASE_NAME = "People_db_1";
    private static final String DATABASE_TABLE = "people_table";
    private static final int DATABASE_VERSION = 1;


    private static class Dbhelper extends SQLiteOpenHelper {

        public Dbhelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub

            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
                    + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_NAME
                    + " TEXT NOT NULL, " + KEY_PASSWORD + " TEXT NOT NULL); ");

        }


        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

            db.execSQL("DROP TABLE IF EXISTS" + DATABASE_TABLE);
            db.execSQL("ALTER TABLE " + DATABASE_TABLE +" ADD COLUMN "+ KEY_AGE +" TEXT NOT NULL ; ");
            onCreate(db);

        }

    }
like image 446
SAGA Avatar asked Dec 12 '25 17:12

SAGA


2 Answers

Database Upgrading

The constructor of your implementation of SQLiteOpenHelper should call the super constructor, passing along the database name and version. The onUpgrade() method will only be called when the version integer is larger than the current version running in the emulator. If you want the onUpgrade() method to be called, you need to increment the version number in your code.

See More about onCreate() and onUpgrade()

like image 149
Tikitaka Avatar answered Dec 15 '25 08:12

Tikitaka


I don't think there is ALTER COLUMN in sqlite.

Just follow the steps as suggested in this link

Let me know if it's helped.

like image 28
TheLittleNaruto Avatar answered Dec 15 '25 08:12

TheLittleNaruto