Android SQLite Insert or Update

后端 未结 8 1920
太阳男子
太阳男子 2020-12-04 09:38

as can be seen in the documentation the syntax to make insert or update is : INSERT OR REPLACE INTO

() VALUES (), my
相关标签:
8条回答
  • 2020-12-04 10:29

    this is your method SQLiteDatabase.insertWithOnConflict(). to understand what it does refer to this document on sqlite

    0 讨论(0)
  • 2020-12-04 10:31

    I had the same issue, but I realized when my object already has an Id it should be updated and when it does not have an Id it should be inserted so this is step by step what I did to resolve the issue:

    1- in your object getId use Integer or initialize the Id how you see fit: here is my code

    public Integer getId() {
        return id;
    }
    

    2- check the Id in your method for insert or update after you put everything in ContentValues:

    if(myObject.getId()!= null ){
            int count = db.update(TABLE_NAME,myContentValues,ID + " = ? ",
                    new String[]{String.valueOf(myObject.getId())});
            if(count<=0){
                //inserting content values to db
                db.insert(TABLE_NAME, null, myContentValues);
            }
        } else {
            db.insert(TABLE_NAME, null, myContentValues);
        }
    

    what happens here is that I check for Id if does exist I update that row but if update method returns -1 it means there were no rows with that Id so I insert the row, and if it does not have an Id I insert it.

    hope this helps.

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