Error:Not sure how to convert a Cursor to this method\'s return type
Error:Execution failed for task \':app:compileDebugJavaWithJavac\'.
Compilation failed; see the
in case someone actually needs MutableLiveData<List<T>>
in their ViewModel when working with Room
and using Kotlin
and coroutines
, this is how I've solved it
In the Dao I get MutableList with suspend
In the repository I change the context to Dispatchers.IO
and extract the list with suspend
in the ViewModel I use postValue
with the list in the init, syntax is below
ViewModel
private val allItems = MutableLiveData<List<DocumentItem>>()
init {
viewModelScope.launch {
allItems.postValue(repository.getAll())
}
}
Repository
suspend fun getAll(): MutableList<DocumentItem> = withContext(Dispatchers.IO) {
dao.getAll()
}
Dao
@Query("SELECT * FROM document_items ORDER BY id DESC")
suspend fun getAll(): MutableList<DocumentItem>
Modify your Dao, use Flowable instead of observable and add the following dependency (room with rxjava support)
compile group: 'android.arch.persistence.room', name: 'rxjava2', version: '1.1.1'
Dao returns flowable:
@Query("SELECT * FROM TableX")
public abstract Flowable<List<EntityX>> getAllXs();
For anyone landing here, using a coroutine Flow as a return type, you will get this error if you accidentally make the function suspend. Since it is returning a flow, there is no need to suspend.
So instead of this:
@Query("SELECT * FROM myTable WHERE id = :id")
suspend fun findById(id: Long): Flow<MyDataType>
use this (without suspend modifier):
@Query("SELECT * FROM myTable WHERE id = :id")
fun findById(id: Long): Flow<MyDataType>
I Spend the entire day on this issue. the solution was very simple. I was using something like this before
@Query("SELECT * FROM myTable")
fun getAll(): MutableLiveData<ArrayList<myData>>
Now when I changed ArrayList to List & MutableLiveData to LiveData it is working fine.
@Query("SELECT * FROM myTable")
fun getAll(): LiveData<List<myData>>
based on the answers & comments on this issue I think room support only List & LiveData because I tried with on MutableLiveData & only ArrayList too. none of the combinations worked.
Hope this will help someones few hours.
Add the below code inside defaultConfig in build.gradle
javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true
In my case i was this problem when i used LiveData<ArrayList<Example Class>>
in Dao class for getting all things from Room and i fixed this when i change ArrayList
with List
.
Example(Kotlin):
@Dao
interface ExampleDao {
@Query("SELECT * from example_table")
fun getAllExample():LiveData<List<Example>>
}