Skip to content
Advertisement

How to update the value of the existing columns in SQLite android ? (not able to do in my project)

I am trying to update the existing column of my table but am not able to do so…. There are no errors it is just not getting updated. My code are there below


Calling the function by passing value a is the _id in which i want to change and i is the value which i want to insert.

     boolean isUpdate = mDbHelper.updatedata(String.valueOf(a),String.valueOf(i));

The function which I am using to change the values

 public boolean updatedata(String id,String books){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS,books);

        Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});
        
            long r = db.update("Library_Student",contentValues,"books=?",new String[]{books});
            if (r == -1){
                return false;
            }else {
                return true;
            }
            
    }

Here is the table which i need to edit..

    String SQL_CREATE_LIBRARY_TABLE_STUDENT = "CREATE TABLE "+ Lib_student.TABLE_NAME + " ("
                +Lib_student._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                +Lib_student.COLUMN_STUDENT_NAME+ " TEXT NOT NULL, "
                +Lib_student.COLUMN_STUDENT_EMAIL+ " TEXT, "
                +Lib_student.COLUMN_STUDENT_AGE+ " INTEGER , "
                +Lib_student.COLUMN_STUDENT_GENDER+ " TEXT ,"
                +Lib_student.COLUMN_STUDENT_NUMBER+ " INTEGER ,"
                +Lib_student.COLUMN_STUDENT_ADDRESS+ " TEXT ,"
                +Lib_student.COLUMN_STUDENT_BOOKS + " INTEGER );";

Advertisement

Answer

First, there is no need to select the row that you want to update, so remove this line:

Cursor cursor = db.rawQuery("select * from Library_Student where books=?",new String[]{books});

Also, you must pass the id and not the value of books as an argument to the method update():

public boolean updatedata(String id, String books) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Lib_student.COLUMN_STUDENT_BOOKS, books);
    return db.update("Library_Student", contentValues, Lib_student._ID + " = ?", new String[]{id}) > 0;
}

The method update() returns the number of the updated rows (it never returns -1), so you must compare that number to 0 and return true if it is greater than 0 or false if it is 0.

7 People found this is helpful
Advertisement