Home > OS >  How to query a list inside Room database in android?
How to query a list inside Room database in android?

Time:07-28

This is the class that i'm saving inside room database:

@Entity
data class Person(
    val name : String = "Bruno",
    val age : Int = 23,
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val hobbies : ArrayList<String> = arrayListOf("Basquete","Academia","Musica","Anatomia")
)

I already added type converters so it is saving successfully. What i want is to query results by what the hobbies list has. E.g:

select * from person where hobbies in ("Basquete")

I wanted to select all person objects that has "Basquete" inside the hobbies list, but this query is returning empty. What am i doing wrong?

CodePudding user response:

Their is no concept of a list in a row of a table, a column holds a single value.

Having a Type Converter will store the list of hobbies as a single value (column), as such IN will check the entire (the EXACT) value (the full list and whatever encoding is used, this dependant upon the Type Converter that converters the list to the single value).

  • As such it is likely that using IN, is not going to be of use.

  • As an example the TypeConverter may convert to something along the lines of ["Basquete","Academia","Musica"] (conversion to JSON string via com.google.code.gson dependcy)

To demonstrate using data loaded and using App Inspection then with

  • enter image description here:-

Now consider an adaptation of your query, it being SELECT *, hobbies in ("Basquete") AS TEST1, hobbies IN ('Basquete') AS TEST2, "Basquete" IN(hobbies) AS TEST3,'Basquete' IN (hobbies) AS TEST4 ,hobbies LIKE '

  • Related