4

We want to build a filter for a room database, where the filter options are selected by the user.

i.e. we have an entity with field (id, name, date, type) the user may filter a list by date between and/or name contain text and/or type equals something

Is there a way to do this in room?

Charlie Wu
  • 7,657
  • 5
  • 33
  • 40

1 Answers1

3

I'm sorry to say that this is not currently possible in the way you want.

I have managed to do it by using the db.query(query, values) method. Generate your your query string at runtime (with placeholders '?'), and pass an array of runtime generated values. Note that this will return a Cursor, not an instance of the specific object you want, so you will have to define a method for mapping the Cursor to a POJO.

I've attached some links to my Cursor2Pojo Mapper and an project implementing it. Feel free to use it, as it should solve your problem in a somewhatgraceful manner. It supports list and single instance returns, although requires you add more annotations to your class (Room annotations are class bound so you cannot get them through reflection at runtime)

Cursor2Pojo custom lib

Project Implementation at line 66 - 72

Jack Dalton
  • 3,536
  • 5
  • 23
  • 40