Room "Not sure how to convert a Cursor to this method's return type": which method?

AndroidDaoAndroid RoomKaptAndroid Architecture-Components

Android Problem Overview


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 compiler error output for details.

Using Room I'm getting this error and I'd like to find out which method causes it.

I have multiple DAOs, with approximately 60 methods in total, and this error just popped up after adding a method (copy&pasted from another one that worked perfectly, just changed the field to set).

I could post the whole class of DAOs, but I'm asking for a way to know which method failed. I tried with Run with --stacktrace, Run with --info and --debug option, but none of these show any valuable information.

The method I added is a @Query UPDATE with Int return type, as suggested in the documentation

> UPDATE or DELETE queries can return void or int. If it is an int, the value is the number of rows affected by this query.

EDIT: I'd like to add that I tried deleting the method, bringing the DAO back to the working state, but it still gives me this error.

EDIT2: Adding gradle console output because unreadable in comments:

error: Not sure how to convert a Cursor to this method's return type
error: Not sure how to convert a Cursor to this method's return type
2 errors

:app:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 22s

Android Solutions


Solution 1 - Android

Recently I've had the same problem but I was using Coroutines within the Dao function, e.g.:

@Query("SELECT * FROM Dummy")
suspend fun get(): LiveData<List<Dummy>>

And was unable to compile, but after removing the suspend everything worked just fine. It's not needed when returning LiveData. suspend and LiveData seem not to work together (as of now).

Solution 2 - Android

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.

Solution 3 - Android

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> 

Solution 4 - Android

Yup, based on what you have mentioned in the comments, you are not allowed to change the return type from List to anything else inside the Dao. I'd assume Room doesn't know how to deal with other return types. Take the List and cast/convert it into your desired type outside of the Dao.

Solution 5 - Android

It is gone after I updated to latest version Room - room_version = "2.4.0"

Solution 6 - Android

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>>
}

Solution 7 - Android

@Query("select * from movie_action")
    suspend fun getMovieActionRoom() : LiveData<List<MoviesActionModel>>

just remove suspend and the error will be gone in some cases.

Solution 8 - Android

For me it was because of mixing AndroidX with Pre-AndroidX. After a full migration and performing this, everything was back to normal. (Of course I moved to AndroidX-Room as well)

Solution 9 - Android

I've got a different use case for my apps.

So, I'm trying to return the actual Cursor type.

E.g:

@Query("SELECT * FROM tbl_favourite")
abstract suspend fun selectAll(): Cursor

The above code will always throw Error:Not sure how to convert a android.database.Cursor to this method's return type

But as I recall correctly, the official docs also stated here that Room supports Cursor.

After trying to debug the error log, and open up the MyTableDao_Impl.java file I've found that looks like Cursor are having an unhealthy relationship with suspend keywords.

Thus, I've corrected my code to be like this:

@Query("SELECT * FROM tbl_favourite")
abstract fun selectAll(): Cursor

And voila, it works.

Solution 10 - Android

In my case I was using androidx dependencies for Room and android.arch. [old] dependencies for ViewModel and LiveData so I got this message

Solution: Either use all androidx dependencies OR use all old dependencies of andrio.arch

Solution 11 - Android

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>

Solution 12 - Android

For my case, after got "Not sure how to convert a Cursor to this method's return type”:

delete the "build" and re-build, the error disappear.

Solution 13 - Android

Add the below code inside defaultConfig in build.gradle

javaCompileOptions.annotationProcessorOptions.includeCompileClasspath = true

Solution 14 - Android

For me, I was using wrong return type for queries.

Solution 15 - Android

Make sure if there is

> There is a problem with the query: [SQLITE_ERROR] SQL error or missing > database (no such table: METRO)


error in your build log before the error you mentioned in your description. If it is, you may have forgotten to add your new entity Pojo to database class. something like this

@Database(entities = {Table.class,ForgottenTable.class}, version = 1) 
public abstract class Database extends RoomDatabase {
    //class codes
}

Solution 16 - Android

Make sure you are not using suspend together with LiveData as return type:

@Query("SELECT * FROM ...")
fun getAllTellsByReceiver(receiverUid: String): LiveData<List<Tell>>

Solution 17 - Android

 class IdAndFullName {
     public int uid;
     @ColumnInfo(name = "full_name")
     public String fullName;
 }
 // DAO
 @Query("SELECT uid, name || lastName as full_name FROM user")
 public IdAndFullName[] loadFullNames();

If there is a mismatch between the query result and the POJO, Room will give you this error message.

Or if you are using @SkipQueryVerification, you will also get this error.

Solution 18 - Android

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();

Solution 19 - Android

For me it was to change from MutableLiveData to LiveData as the return type of the get method.

Solution 20 - Android

I got this error when I was trying do some aggregate functions in the query, like sum and count and then using aliases in the column names.

select count(users.id) as userCount, ...

It so happens that the alias name like userCount above, must match the field name in the model.

Solution 21 - Android

You have to include the @Relation annotation in the class returned by the method. It's the only way Room would know how to establish the relationship between the two.

Solution 22 - Android

In my case Room didn't know sure how to convert a Cursor to this method's return type i.e ArrayList so I changed a little bit I converted to list to kotlin's MutableListOf. Now it works fine.

Solution 23 - Android

In my case upgrading versions worked.

Previous

api 'androidx.room:room-runtime:2.0.0'
annotationProcessor 'androidx.room:room-compiler:2.0.0'
api 'androidx.room:room-rxjava2:2.0.0'

Now

api 'androidx.room:room-runtime:+'
annotationProcessor 'androidx.room:room-compiler:+'
api 'androidx.room:room-rxjava2:+'

+ means latest version and for me it was 2.4.2

Solution 24 - Android

This error goes away after I changed the Kotlin version from 1.5.21 back to 1.3.61

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid CorsaliniView Question on Stackoverflow
Solution 1 - AndroidDanilo LemesView Answer on Stackoverflow
Solution 2 - Androidakshay bhangeView Answer on Stackoverflow
Solution 3 - AndroidgMaleView Answer on Stackoverflow
Solution 4 - AndroidAli KaziView Answer on Stackoverflow
Solution 5 - AndroidchethanView Answer on Stackoverflow
Solution 6 - AndroidFidan BacajView Answer on Stackoverflow
Solution 7 - AndroidFelipe FrancoView Answer on Stackoverflow
Solution 8 - AndroidTanasisView Answer on Stackoverflow
Solution 9 - AndroidmochadwiView Answer on Stackoverflow
Solution 10 - AndroidMakarandView Answer on Stackoverflow
Solution 11 - AndroidStachuView Answer on Stackoverflow
Solution 12 - AndroidDavid GuoView Answer on Stackoverflow
Solution 13 - AndroidVijayView Answer on Stackoverflow
Solution 14 - AndroidIrshuView Answer on Stackoverflow
Solution 15 - AndroidRezaView Answer on Stackoverflow
Solution 16 - AndroidAndré RamonView Answer on Stackoverflow
Solution 17 - Androidlive-loveView Answer on Stackoverflow
Solution 18 - AndroidMr.QView Answer on Stackoverflow
Solution 19 - AndroidOtziiiView Answer on Stackoverflow
Solution 20 - Androidmike.kamauView Answer on Stackoverflow
Solution 21 - AndroidAspiring DevView Answer on Stackoverflow
Solution 22 - Androidgouri pandaView Answer on Stackoverflow
Solution 23 - AndroidGowtham GowdaView Answer on Stackoverflow
Solution 24 - AndroidmujeebView Answer on Stackoverflow