1

I have searched alot but couldn't get a solution.

I initially got this error

error: Query method parameters should either be a type that can be converted into a database column or a List / Array that contains such type. You can consider adding a Type Adapter for this.
    androidx.sqlite.db.SupportSQLiteQuery query);

So after searching a bit, decided to add the @TypeConverter annotation and the @TypeConverters() annotation in the database class

This is the error I am getting now. error: Type converters must receive 1 parameter. public final androidx.sqlite.db.SimpleSQLiteQuery getAllQuery(@org.jetbrains.annotations.NotNull()

My DAO has this -

@Query("SELECT * FROM tea WHERE name == :name")
    fun getTea(name: String): LiveData<Tea>

My TypeCoverter class has this method

 @TypeConverter
    fun getAllQuery(sortBy: TeaSortBy, showOnlyFavorites: Boolean): SimpleSQLiteQuery {
        val queryBuilder = SupportSQLiteQueryBuilder
                .builder(DataTeaNames.TABLE_NAME)
                .orderBy(getSortColumn(sortBy))
        if (showOnlyFavorites) {
            queryBuilder.selection(DataTeaNames.COL_FAVORITE, arrayOf("1"))
        }
        return SimpleSQLiteQuery(queryBuilder.create().sql)
    }

In the repositroy:

fun getSortedTeas(sort: String, fileByFavorite: Boolean = false): LiveData<PagedList<Tea>> {
        val sortBy = SortUtils.TeaSortBy.valueOf(sort)
        val factory = dao.getAll(SortUtils.getAllQuery(sortBy, fileByFavorite))
        return LivePagedListBuilder(factory, PAGE_SIZE)
                .build()
    }

Apologies in advance, I am new to this use of TypeConverters in Room Database. I would really appreciate your help. Thank you.

Shizuku
  • 147
  • 1
  • 9

2 Answers2

2

A class with a method to help Room understand the Tea class annotated with @TypeConverter is required.

For example: (using Gson)

class TeaConverter {
    @TypeConverter
    fun toTeaList(json: String): List<Tea> {
        val type = object : TypeToken<List<Tea>>(){}.type
        return Gson().fromJson(json, type)
    }

    @TypeConverter
    fun toJson(teaList: List<Tea>): String {
        val type = object: TypeToken<List<Tea>>(){}.type
        return Gson().toJson(torrent, type)
    }
}

Then add this converter to you database like:

@TypeConverters(TeaConverter::class)
abstract class TeaDatabase : RoomDatabase() {}
Darshan
  • 4,020
  • 2
  • 18
  • 49
  • Thanks for the info! Turns out it was a mismatch of Kotlin and Room versions that caused my initial error and the missing @RawQuery annotation. Had nothing to do with TypeConverters. – Shizuku Nov 08 '21 at 13:35
0

Turns out it was a mismatch of Kotlin and Room versions that caused my initial error as referred from this answer - https://stackoverflow.com/a/68052960/8442557

Also, I missed adding a @RawQuery annotation.

This solved my error.

Shizuku
  • 147
  • 1
  • 9