0

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!

2
  • are you using room database? at least add some code snippet that you have tried so that we can help you with that Commented Sep 28, 2021 at 5:41
  • @unownsp no i am using SQLite. Commented Sep 28, 2021 at 7:45

2 Answers 2

1

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.