1

I am using Room Persistence Library. The operation works as expected. But how do I get onConflict value from DAO back from calling method. I get the following error

error: Not sure how to handle the insert method's return type.

Update After I change return type from Integer to long, I get this error

Not sure how to handle update method's return type. Currently the supported return types are void, int or Int.

In DAO.java

@Dao
public interface UserDao {

    @Insert(onConflict = OnConflictStrategy.ABORT)
    long insert(UserEntity userEntity);

    @Update(onConflict = OnConflictStrategy.IGNORE)
    long update(UserEntity userEntity);
}

In MainActivity.java

@Override
protected Void doInBackground(UserEntity... userEntities) {
    long result = userDao.insert(userEntities[0]);
    if(result == OnConflictStrategy.ABORT){
        result = userDao.update(userEntities[0]);

    }
    return null;
}
ansonk163
  • 63
  • 3
KIRPAL SINGH
  • 185
  • 2
  • 17
  • see this https://stackoverflow.com/questions/44364240/android-room-get-the-id-of-new-inserted-row-with-auto-generate – iamkdblue Jun 04 '19 at 06:50
  • @kdblue i tried changing from Integer to Long as suggested, it showing error above. See my updated question – KIRPAL SINGH Jun 04 '19 at 07:06

2 Answers2

2

In case of ConflictStrategy.ABORT Room will throw a SQLiteConstraintException. You can catch that to fit your use case.

The compilation error you are getting is due to the fact @Insert operations can return long, long[] or void only. Integer will not do.

@Update will return the number of rows updated by the query. This method will return an int or void. Doc: https://www.sqlite.org/lang_update.html

Arka Prava Basu
  • 2,366
  • 3
  • 18
  • 34
1

Insert If the @Insert method receives only 1 parameter, it can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List instead.

Update Although usually not necessary, you can have this method return an int value instead, indicating the number of rows updated in the database.

After reading multiple time, i understood the methods are returning number of records instead of error code. Anyway my question regarding how OnConflictStrategy values are read or used is still unanswered

KIRPAL SINGH
  • 185
  • 2
  • 17
  • 1
    U cant "read" its value. As answered if ABORT it will throw an SQLiteConstraintException. Source: https://commonsware.com/AndroidArch/previews/room-and-conflict-resolution Need to find out of the other states. – Arka Prava Basu Jun 04 '19 at 07:38