performing query operations in Room ORM restarts my application

Viewed 23

I am using Room to save objects in the database. and any time I perform an operation like insert or get all my application restarts.

this is my entity class:

@Entity
class Task(
    @PrimaryKey val id: Int,
    @ColumnInfo(name = "title") val title : String,
    @ColumnInfo(name = "detail") val detail : String
)

this is my database class:

@Database(entities = [Task::class], version = 1)
abstract class AppDatabase : RoomDatabase() {

    abstract fun taskDao() : TaskDao
    companion object{
        var INSTANCE: AppDatabase? = null
        fun getAppDatabase(context: Context): AppDatabase? {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(
                    context,
                    AppDatabase::class.java,
                    "task-database"
                )
                .build()
            }
            return INSTANCE
        }
    }
}

I try calling it from my AndroidViewModel class like this:

class AddTaskViewModel(application: Application) : AndroidViewModel(application) {

    private val context = application

    var title : MutableLiveData<String> = MutableLiveData("")
    var detail : MutableLiveData<String> = MutableLiveData("")

    fun saveTask(){
        val task = Task(id = 1, title = title.value!!, detail = detail.value!! )
        val taskDao : TaskDao? = AppDatabase.getAppDatabase(context)?.taskDao()
        taskDao!!.insertAll(task)
        Toast.makeText(context, "it is done", Toast.LENGTH_LONG).show()
    }

    fun changeTitle(text: String){
        title.value = text
    }

    fun changeDetail(text: String){
        detail.value = text
    }
}

and at the point where taskDao!!.insertAll(task) is called the app restarts.

2 Answers

I think the issue might be that when you are inserting tasks into your database the id which is supposed to be the primary key is violated, in the sense that it's not unique, so the unique constraints fail

val task = Task(id = 1, title = title.value!!, detail = detail.value!!) Try incrementing the id for example or letting room do that for you

I had to run the function in a coroutine because it was locking the UI processas seen in this post

Related