updating method using content values

后端 未结 1 968
轮回少年
轮回少年 2021-01-23 12:59

Helper

public boolean mMessagesSent(String ID,int Data) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues =          


        
1条回答
  •  独厮守ぢ
    2021-01-23 13:24

    Is this the correct method to update data... I want to increase the int value of data by 1 so i have put +1 but still the value is empty when i retrieve data

    If you meant to increase the existing value of data by once each time you call the function mMessagesSent()

    You can consider to first take the value from the database if it exists, and increment the value. Create a function in Helper as shown below

    public Cursor getData(){
    
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_NAME;
    
        return db.rawQuery(query, null);
    }
    

    This will return a Cursor to the Database, to read the values in the database. Do not put the function mMessagesSent in Helper class, put it in the Activity. Now in your mMessagesSent function, call the above function getData() as shown

    public void mMessagesSent() {
    SQLiteDatabase db = this.getWritableDatabase();
    String newId = "default value whatever you have specified";//These two lines may be removed and put outside. If you already have it, then 
    int newData = 0;                                           //not required to declare here at all, just replace with those variable names
    HelperClassName helper = new HelperClassName(this); //Change the name to your Helper Class name
    Cursor data = helper.getData();
    while(data.moveToNext()){
        newId = data.getString(0);
        newData = data.getInt(1);
    }
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_ID, ID);
    contentValues.put(KEY_MESSAGES_SENT, (newData+1)); //Change the value of newData(which is actually your old value) by incrementing
    long returnVariable = db.update(TABLE_USER_DATA, contentValues, null, null);
    if(returnVariable == -1){
        //-1 means there was an error updating the values
    }
    else{
    //the return value if successful will be number of rows affected by the update
    }
    } 
    

    I hope you got your answer.

    0 讨论(0)
提交回复
热议问题