Search code examples
androidkotlinandroid-roomkotlin-coroutines

Not sure how to convert a Cursor to this method's return type after Kotlin update to 1.6.0


I was using Android Room library in my project to manipulate data from my SQLite database and everything was working fine in previous Kotlin version (1.5.31). Here is a sample of my DAO:

@Dao
interface ServersDao {

    @Query("SELECT * FROM servers ORDER BY connectedDevices, ping ASC LIMIT 1")
    suspend fun getLeastLoadedServer(): Server

    @Query("SELECT * FROM servers ORDER BY ping, connectedDevices ASC LIMIT 1")
    suspend fun getNearestServer(): Server
}

After updating Kotlin to version 1.6.0, my code couldn't compile anymore, and I am receiving this error:

error: Not sure how to convert a Cursor to this method's return type (java.lang.Object). public abstract java.lang.Object getLeastLoadedServer(@org.jetbrains.annotations.NotNull()

After some searching, I read that it was because of suspending functions, so I removed suspend keyword from my DAO, and I started getting the obvious error:

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

Even if I was calling those function from a IO coroutine.

I also read through the change log of Kotlin 1.6.0, that did not help much.

Any help is appreciated, thanks.


Solution

  • Using Android Room 2.4.0 will solve the issue.

    For Kotlin 1.7.10, you need to use Room 2.5.0-alpha02 or newer.