I am using the SQLite database to save some information locally. I want to update the row with the same userID each time while saving new data for that particular userID. But it should insert the data to a new row with the new userID and insertion should work the first time also. Appreciate the help!
CodePudding user response:
if you are using room database you can insert/update as follow:
AppDatabase appDatabase = Room.databaseBuilder(Activity.this, AppDatabase.class, "db_name")
.fallbackToDestructiveMigration()
.allowMainThreadQueries()
.build();
DatabaseItems databaseItems = new DatabaseItems();
databaseItems.setId(userID);
databaseItems.setName(name);//set other needed data
try {
appDatabase.getDatabaseItemDAO().insertItem(databaseItems);
Toast.makeText(Activity.this, "Added", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onClick: =======================> added");
} catch (Exception e) {
appDatabase.getDatabaseItemDAO().updateItem(databaseItems);
Toast.makeText(Activity.this, "Updated", Toast.LENGTH_SHORT).show();
Log.d("TAG", "onClick: ==========================> updated");
}
in this logic if your database already has a item with the id then updateItem will be called in 'catch'
you database item DAO should look something like this:
@Dao
public interface DatabaseItemsDAO {
@Insert
void insertItem(DatabaseItems databaseItems);
@Update
void updateItem(DatabaseItems databaseItems);
}
CodePudding user response:
You can use this code for update data for a specific row
val db = this.writableDatabase
val values = ContentValues()
values.put(TITLE, tasks.title)
values.put(EMAIL, tasks.email)
values.put(PWD, tasks.pwd)
val success = db.update(TABLE_NAME, values, "$ID=?", arrayOf(id)).toLong()
db.close()