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.