Upgrading database version automatically

sam picture sam · Apr 7, 2013 · Viewed 7.5k times · Source

Hi i am creating an app which stores the password of the user entering. and whenever he needs to change his password then the data has to be changed. The problem i am facing is while i am calling the DBHelper class (i created to do all my database works) its not deleting the table if it is available.

It will be more helpful if someone tells me how to delete the entries in the table while calling the DBHelper class.

I realized that the OnCreate and OnUpgrade functions are not executing except the first time while creating the database.

also changing database version automatically also helps i guess but i don't know how to do?? here is my code from DBhelper class

public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
          db.execSQL("DROP TABLE IF EXISTS '" + DATABASE_TABLE+"'");
          db.execSQL("CREATE TABLE " + DATABASE_TABLE +" (" +
                KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "+
                KEY_ID +" INTEGER, "+
                KEY_X +" INTEGER,  "+
                KEY_Y +" INTEGER);"
                );  

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS '" + DATABASE_TABLE+"'");
        onCreate(db);
    }

public long createEntry(int name, int sx, int sy) {
        // TODO Auto-generated method stub
        ContentValues cv=new ContentValues();
        cv.put(KEY_ID, name);
        cv.put(KEY_X, sx);
        cv.put(KEY_Y, sy);
        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

Answer

Boris Strandjev picture Boris Strandjev · Apr 7, 2013

Changing a row in the database should not affect the schema version. This should be executed as proper queries to manipulate the database entries.

You might find use of this method:

public void clearDatabase(Context context) {
   DatabaseHelper helper = new DBHelper(context);
   SQLiteDatabase database = helper.getWritableDatabase();
   database.delete(DATABASE_TABLE, null, null); //erases everything in the table.
   database.close();
}