I am using Room Db using coroutines in kotlin. This is my Dao interface:
@Dao
interface CheckListNameDao {
@Insert
suspend fun insertName(name: CheckListName)
@Query("SELECT * FROM CheckListNamesTable")
fun getAllNames(): LiveData<List<CheckListName>>
}
getAllNames()
method works fine. The problem is with the insertName()
method. When I remove the suspend
keyword from the insertName()
method, it throws this exception: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
But, when I use suspend
keyword, I cannot build the project anymore. It shows the following error:
error: Methods annotated with @Insert can return either void, long, Long, long[], Long[] or List<Long>.
public abstract java.lang.Object insertName(@org.jetbrains.annotations.NotNull()
Why this error is showing? My code is based on this Android Room with a View - Kotlin
Edit: This is my repository:
class MainRepository(application: Application) {
private var nameDao: CheckListNameDao = AppDatabase.getDatabase(application.applicationContext)
.checkListNameDao()
fun getAllNames(): LiveData<List<CheckListName>> {
return nameDao.getAllNames()
}
suspend fun setNewListName(checkListName: CheckListName) {
nameDao.insertName(checkListName)
}
}
This is the viewmodel:
class MainViewModel(application: Application) : AndroidViewModel(application) {
private var mainRepository = MainRepository(application)
fun getAllNames(): LiveData<List<CheckListName>> {
return mainRepository.getAllNames()
}
fun setNewListName(name: String) {
viewModelScope.launch {
mainRepository.setNewListName(CheckListName(0, name))
}
}
}
EDIT 2:
I am also getting this error when I add the suspend
keyword:
error: Type of the parameter must be a class annotated with @Entity or a collection/array of it.
kotlin.coroutines.Continuation<? super kotlin.Unit> p1);
This is the CheckListName
data class:
@Entity(tableName = "CheckListNamesTable")
data class CheckListName(
@PrimaryKey(autoGenerate = true)
var id: Int,
var name: String
)
Long
return type and the error still shows up. – Hardening