In my android app, I am using the realmBaseAdapter to dynamically display data from a realm query. I was wondering if there is any way to sort these results within the adapter so that I can group them based on certain properties.
Yes, you can :)
You can you build your RealmResults like this:
RealmResults<User> results = realm.where(User.class).findAllSorted(
"name", RealmResults.SORT_ORDER_ASCENDING);
or sort the it after build it like:
RealmResults<User> result = realm.where(User.class).findAll();
result.sort("age"); // Sort ascending
result.sort("age", RealmResults.SORT_ORDER_DESCENDING);
You can also sort by multi fields like:
RealmResults<AllTypes> results = testRealm.where(AllTypes.class)
.findAllSorted(new String[]{"name", "age"},
new boolean[]{RealmResults.SORT_ORDER_ASCENDING,
RealmResults.SORT_ORDER_ASCENDING});
See Doc of RealmQuery and RealmResults.
You don't have to sort the result every time before using it. Once the results is sorted, it will be sorted even when the database changed and results get updated.
Related
I have a recyclerview using Firestore Recyclerview Adapter, Now I want to show the list by using OR query.
For example I want to show the list which are either in "Pending" state OR "Assigned" state using query. I know firestore doesn't have OR query inbuilt but I want to achieve this anyhow. Any alrernative solution.
I have stored 4 state in firestore db : Pending, Assigned, Accepted and Completed.
Only want to show pending or assigned
Below is my code:
Query query = requestVehiclesCollectionReference
.whereEqualTo("clientId", id)
// show list which are in Pending state or Assigned state
.whereEqualTo("status", "Pending")
.orderBy("createdAt", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Item> options = new
FirestoreRecyclerOptions.Builder<Item>()
.setQuery(query, Item.class)
.build();
Firestore doesn't support queries with OR conditions. See:
Implementing OR in firestore query - Firebase firestore
How to perform compound queries with logical OR in Cloud Firestore?
Firebase Firestore - OR query
The common workaround is to use multiple queries (one for each condition) and merge the results in your application code.
FirebaseUI's adapters show data from a single query or collection. They have no option to show the results from multiple queries/collections.
From this combination it follows that you can't show data from an OR condition with a single FirebaseUI adapter. You will have to create you own adapter for this, although you can certainly use the (open-source) FirebaseUI adapters for inspiration.
I am using liveData in my application. I do a DB Query which returns a LiveData<PagedList<Contact>> of contacts stored in DB.
I want to modify this livedata before giving it to observers. Suppose there are ten contacts in the LiveData list, i want to do some comparison with another list and set which contacts are primary in the LiveData list.
After doing this i want to give it to observers .
e.g -
val allContacts: LiveData<PagedList<Contact>> = getFromDB()
val list: ArrayList<String>() = list of some primary contacts
traverse allContacts and list and set which values in allContacts match the values in list.
which ever values in allContacts match, their isPrimary property will be set to true.
Now after modifying allContacts, i want to submit it to observers like:
allContacts.observe(this, Observer(adapter::submitList))
I tried LiveData.transform, But not able to use it properly.Can anyone suggest me how to achieve it using transform method or some other way.
What you are looking for is a Transformation. Use Transformations.map() to create a new LiveData from a function that will be run everytime the first LiveData changes.
e.g.
val allContacts: LiveData<PagedList<Contact>> = getFromDB()
val contactViewModel = Transformations.map(allContacts, {
// Transform and create new list from old
})
Your problem is rooted in the fact that you wish to "intercept" the updates that will be posted to the LiveData object by the DB. Regardless if this is a good approach you can technically achieve it by wrapping the LiveData that is returned by the DB with your own subclass of LiveData.
In other words. UI --observes--> YourLiveData --observes--> DBLiveData
P.S. I think genrally speaking you could solve your problem by modifying your DB query, but that is just me assuming you already have "primary contacts" in some other table
How can I change the order or index of Realm object in the android studio??
I want to change the order of the objects, I cleared the class and tried to insert a new one, Is that the solution. Please help me
Instead of using findAll() method you can use findAllSorted() and you can also give ASCENDING or DESCENDING order.
From Realm documentation:
findAllSorted(java.lang.String[] fieldNames, Sort[] sortOrders)
Finds all objects that fulfill the query conditions and sorted by
specific field names.
Parameters:
fieldNames - an array of field names to sort by.
sortOrders - how to sort the field names.
Returns: a RealmResults containing objects. If no objects match the
condition, a list with zero objects is returned.
I just inserted a column sort_order and updated that each time.
Works perfectly. Thanks
I currently have a list of userIds and I am trying to create a query to get all of those from my DB.
this is what I have in mind, I'm just not that sure that it's possible:
ArrayList<Users> listOfUsers = getCurrentUsers();
// lets assume that by now I have a list of users
QueryBuilder<Users> qb = getUsersDao().queryBuilder();
for(Users usr : listOfUsers) {
qb.where(Properties.userId.eq(usr.getUserId());
}
List result = qb.list();
I haven't seen any documentation about what is the right way of doing this and I want to know if this is the correct way of creating a dynamic query in GreenDAO.
EDIT:
I tried this and the result was a NullPointerException in the line of the declaration on the QueryBuilder
try using the IN query instead, it will run faster + you can cache your Query object.
so lets say you have
List<String> userIds;
you can get the list with:
qb.where(Properties.UserId.in(userIds))
if this is an operation that you do frequently, it is better to cache the Query. to do that, prepare the query as follows for only once:
Query<User> query = qb.where(Properties.UserId.in("?")).build();
then when you need to run it :
query.setParameter(0, userIds);
return query.list();
I'm writing a simple database app on Android. The main activity is just a list of products - a ListActivity using a CursorAdapter. How is the best way to go about changing the order of the list (is sort by Price or ProductID or something). I'm guessing I need to execute a new query to get a new cursor - or can I recycle things?
There are two options base specialized on your app:
How many record in your db ( If your database too large, new query may take long time)
Your app usual query to database to get data
New query is simple better if your database not too large and your app not usual query to get data. In otherwise try create custom adapter
A cursor adapter - perfect! That means you're getting the list through a query. Just change the sort order. All commands that perform queries have an optional "sort order" parameter.