I am trying to sort my data by ascending and descending order using room database. So I need to pass those parameter to the DAO.
This is my code:
#Query("SELECT * FROM DEVICES_TABLE ORDER BY :sortQuery")
fun sortDatabase(sortQuery: String): Flow<List<DeviceData>>
But when I pass title DESC as sortquery (title is column name), the query becomes:
SELECT *
FROM DEVICES_TABLE
ORDER BY 'title ASC'
I need to remove those single quotes from query for achieving the results. I need to sort with title, price, type etc. both ascending and descending. How can I do that?
Related
i have a query like this
#Query("SELECT * FROM table WHERE type IN(:types) AND selection = 0 ORDER BY timestamp DESC")
my problem is that i have one type in my type list lets say it's type=4 for which i want selection = 1.
Is it possible to get the results in one query and how should the query look like?
I am loading a set of data from db using room and pagedList since it is a large set. I need to filter that data and show it to the user accordingly using the same pagedlistadapter. Please help.
dao is as follows
#WorkerThread
#Query("SELECT * FROM users WHERE name LIKE :query ORDER BY id DESC")
fun getAll(query: String): DataSource.Factory<Int, users>
Table has 4 fields - id,name,phone,address
You should use Transformations.switchMap() to requery the database any time the search term changes:
https://github.com/gavingt/upcoming-games/blob/cd7af7fbdd60933991ea7f8b966ca171bb594cb3/app/src/main/java/com/gavinsappcreations/upcominggames/ui/list/ListViewModel.kt#L35
Or see Google's Paging Library codelab, which does the same thing:
https://codelabs.developers.google.com/codelabs/android-paging/index.html?index=..%2F..%2Findex#1
#Query("SELECT * FROM users WHERE name LIKE :query ORDER BY id DESC")
fun getAll(query: String): DataSource.Factory<Int, users>
Here's your query string must be like %ABC% where abc is the name of the user.
The LIKE key word is use to check/find the pattern in the records Here you can read the possible pattern searches
To attach the % % to your query string you need to call this function as
YOUR_HELPER.getAll("%".plus(YOUR_QUERY).plus("%"))
plus() uses for Concatenation.
I want to get data from my room db with the following query:
#Query("SELECT address.address_id, first_name, last_name, street, postal_code, city," +
"(SELECT employee.employee_id FROM employee WHERE employee.address_id = address.address_id) AS employee_id, " +
"(SELECT project.project_id FROM project WHERE project.address_id = address.address_id) AS project_id " +
"FROM address WHERE last_name IN (:pattern) OR first_name IN (:pattern) ORDER BY last_name ASC, first_name ASC")
LiveData<List<AddressBookAddress>> loadAddressBookWithFilter(String... pattern);
As you can see my parameter accepts an array with one or more search strings.
Let's take for example "max" and "muster"
Now I want to get all records which contain the first names "max" or "muster" or the last names "max" or "muster". But currently, I'm not receiving any data at all.
The docs show it as quite straightforward thing. Look at Room Query docs. There you can see this example:
As an extension over SQLite bind arguments, Room supports binding a list of parameters to the query. At runtime, Room will build the correct query to have matching number of bind arguments depending on the number of items in the method parameter.
#Query("SELECT * FROM user WHERE uid IN(:userIds)")
public abstract List findByIds(int[] userIds);
For the example above, if the userIds is an array of 3 elements, Room will run the query as: SELECT * FROM user WHERE uid IN(?, ?, ?) and bind each item in the userIds array into the statement.
So, change signature from "String..." to "String[]" to clearly state an array presence.
There is no document for kotlin on this page but you can use this code for the same.
#Query("SELECT * FROM employee WHERE id IN(:idList)")
fun getAllSelectedEmployee(idList:Array<String?>): List<Model>
I have 2 queryes from ROOM DB:
#Query("SELECT * FROM basket_items")
Flowable<List<BasketItem>> getAll();
#Query("SELECT SUM(count*amount) FROM basket_items")
Flowable<Long> totalSum();
How can I merge this queryes to one query? And what type of model it will be return?
Room Queries can return POJO (not an #Entity), and therefore you can make temporary model for your DAO.
As I already asked in comments, I don't know what you're trying to achieve (as in what value you want to get from those queries).
But hopefully this example might help:
YourDao.java
#Query("SELECT name AS nameItem, (count * amount) AS countItem FROM basket_items")
Flowable<List<CountedBasketItem>> getAllCounted();
static class CountedBasketItem {
String nameItem;
Long countItem;
}
Additional Answer
What you want to return List and total sum is not possible by the query. SUM is aggregation method, you aggregate the list.
So there're 2 options that you might want to do:
Use GROUP BY in your query
Or execute those 2 Flowable and get the result.
you can create field totalSum in your pojo and use this query
#Query("SELECT *,SUM(count*amount) AS totalSum FROM basket_items")
Flowable<List<BasketItem>> getAll();
you will get all table and the field totalSum is SUM(count*amount)
I am using Room as ORM. I want to get array of some objects from it with a specific order. My code looks like this:
#Query("SELECT * FROM `group` WHERE id IN (:ids) ORDER BY id in (:ids)")
But "order by" not works. I don't want just to sort it by field "id". I want to sort it by id that correlate with array "ids". I mean:
I have array of Integer ids = arrayOf(16,12,18,3) and i use it in query above. And on the output i want to have array of some object(say group). The output array will looks like this
ListOf(Group(id:16, name: "someName"),
Group(id: 12, name: "someAnotherName",
Group(id: 18, name: "name"),
Group(id: 3, name: "another"))
So you where quite close. Try using
#Query("SELECT * FROM `group` WHERE id IN (:ids) ORDER BY id")
That should work for you. Im not sure on the group
You using wrong way, ORDER BY id in (:ids) is incorrect
it should be
#Query("SELECT * FROM `group` WHERE id IN (:ids) ORDER BY id")
To retrieve data from database in the order you want is impossible, as the database don't know about current indexes in the array for ids. Actually it's possible, but you have to provide this information in a query or store it beforehand in a table.
What you actually want, is to get corresponding group information by some ids, so
retrieve group data without ordering
#Query("SELECT * FROM group WHERE id IN (:ids)")
fun getGroupsById(): List<Group>`
store the result into a map
val idToGroups = mapOf<Long, Group>()
for (group in getGroupsById()) {
idToGroups[group.id] = group
}
then while iterating over initial ids array, get corresponding groups by id
for (id in ids) {
// here group is related to each position in the array
group = idToGroups[id]
println("Id: ${id}, Name: ${group.name}")
}