Is there a way to dynamically query a database?

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

i.e. we have an object with a field (id, name, date, type) the user can filter the list by date between and / or a name containing text and / or type equal to something

Is there any way to do this in the room?

+5
source share
1 answer

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

I managed to do this using the db.query(query, values) method. Create your query string at runtime (using '?' Placeholders) and pass in an array of generated runtime values. Note that this will return Cursor , not the instance of the specific object you want, so you will need to determine how Cursor displayed in POJO.

I have added some links to my Cursor2Pojo Mapper and the project implementing it. Feel free to use it, as it should solve your problem in a somewhat grim way. It supports the return of lists and individual instances, although it requires the addition of additional comments to your class (number annotations are attached to the class, so you cannot get them through reflection at runtime)

Cursor2Pojo custom lib

Project implementation on line 66 - 72

+3
source

Source: https://habr.com/ru/post/1269705/


All Articles