Android Room Insert or Update

Dec 27, 2018
Perform insert if new, else perform update

Solution 1

Try insert first. If failed, then perform an update.

@Daointerface PinDao {    @Insert(onConflict = OnConflictStrategy.IGNORE)    fun insertIgnore(entity: Pin) : Long    @Update    fun update(entity: Pin)    @Transaction    fun insertOrUpdate(entity: Pin) {        if (insertIgnore(entity) == -1L) {            update(entity)        }    }}

Solution 2

If a row with the same ID already exist, it will delete the existing row and insert a new row. If you are using auto generated ID, this solution probably won't work.

@Insert(onConflict = OnConflictStrategy.REPLACE)fun insertReplace(entity: T) : Long

Solution 3

If you are using auto generated id, you can check if ID is empty and perform insert, else perform update.

If ID is not realiable, you can create an is_new field to help determine if you should perform insert or update.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.