Search code examples
androidmvvmandroid-asynctaskandroid-sqliteandroid-room

Android Room SQLITE Update Custom Query with MVVM


I am trying to do a simple update query where ONE column in a row will be updated. Every example I've seen online does a blanket update where the entire row is updated. I'm using MVVM - Activity, Viewmodel, Repository, AsyncTask, DAO.

It all works fine until I get to the Async task. The doInBackground method is expecting 2 parameters the primary key used to identify the row and the data to be updated. However the Async task only takes on object. So I am not sure how to proceed. Please see snippets below:

 DAO
@Query ("UPDATE CbtTable SET twistedThinkingPK = :twistedThinkingPK WHERE  cbtId = :cbtId")
void updateTwistedThinking(long cbtId, long twistedThinkingPK);

ASYNC
 @Override
protected Void doInBackground(CbtTable... cbtTables) {

    mCbtDao.updateTwistedThinking(cbtTables[0]); // THIS THROWS THE ERROR, IT WANTS THE TWO VARIABLES FORM THE DAO UPDATE QUERY.
    return null;

 REPOSITORY
 public void updateTwistedThinking(CbtTable cbtTable){


    new UpdateTwistedThinkingAsyncTask(cbtDao).execute(cbtTable);
}

 VIEW MODEL
  public void updateTwistedThinking(CbtTable cbtTable){
    cbtRepository.updateTwistedThinking(cbtTable);
}

ACTIVITY
public void updateTwistedThinkingCbtTable(long twistedThinkingPK){

  CbtTable cbtTable = new CbtTable();
  cbtTable.setTwistedThinkingPK(twistedThinkingPK);
  cbtViewModel.updateTwistedThinking(cbtTable);
}

Solution

  • What about trying the following approach?

    @Override
    protected Void doInBackground(CbtTable... cbtTables) {
        CbtTable cbtTable = cbtTables[0]
        mCbtDao.updateTwistedThinking(cdtTable.getCbtId(), cdtTable.getTwistedThinkingPK());
        return null;
     }