I'm getting started in using Realm in my android project..
everything was going well.. But I was trying to filter data but I couldn't.
I want to make a query like this:
SELECT * FROM messages WHERE (fromId='id1' AND toId='id2') OR (fromId='id2' AND toId='id1');
Here's my code :
RealmResults<com.intcore.android.tawasol.Message> results =
realm.where(com.intcore.android.tawasol.Message.class).beginGroup().equalTo("fromId", fromId).equalTo("toId", toId).endGroup().or().
beginGroup().equalTo("fromId", toId).equalTo("toId", fromId).endGroup().findAllSorted("date", true);
but this returns only 1 result.. it should return 2 results.
Any Idea?
Your query looks fine. Try split the query into result and then sort it.
RealmResults<com.intcore.android.tawasol.Message> results;
results = realm.where(com.intcore.android.tawasol.Message.class).
beginGroup().equalTo("fromId", fromId).equalTo("toId", toId).endGroup()
.or().
beginGroup().equalTo("fromId", toId).equalTo("toId", fromId).endGroup()
.findAll();
results.sort("date") // ascending
results.sort("date", RealmResults.SORT_ORDER_DESCENDING); // descending
Related
In my Android app we use couchbase lite database version 2.8.6
I run three database queries.
One item in where clause.
QueryBuilder.select(
SelectResult.property("id"),
SelectResult.property("timestamp"),
SelectResult.property("rating"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string(DOC_TYPE)))
In the result I see three items from database printed to a console. As expected. Format here ans below is id|timestamp|rating
4e39f79c-9e11-4aba-9fb6-95d910f46cd9|0|-2147483648
e95646ee-ba3a-4978-b2a8-5383f31be2f1|0|-2147483648
e02d0eb3-6c9b-4942-b43c-a752eefc77a8|1630525956184|2147483647
I add and() condition to where() to get all items where type = 'type' AND rating < 1
QueryBuilder.select(
SelectResult.property("id"),
SelectResult.property("timestamp"),
SelectResult.property("rating"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string(DOC_TYPE))
.and(Expression.property("rating").lessThan(Expression.intValue(1))
)
Result is as expected as we search everything with rating < 1, third item is filtered out.
4e39f79c-9e11-4aba-9fb6-95d910f46cd9|0|-2147483648
e95646ee-ba3a-4978-b2a8-5383f31be2f1|0|-2147483648
Finally, I want to see records where type = 'type' AND rating < 1 AND timestamp <= 1
QueryBuilder.select(
SelectResult.property("id"),
SelectResult.property("timestamp"),
SelectResult.property("rating"))
.from(DataSource.database(database))
.where(Expression.property("type").equalTo(Expression.string(DOC_TYPE))
.and(Expression.property("rating").lessThan(Expression.intValue(1))
.and(Expression.property("timestamp")).lessThanOrEqualTo (Expression.longValue(1))
)
)
And now the result is really strange as I receive three items form the database. And the third one has timestamp much greater than 1 put into the query.
4e39f79c-9e11-4aba-9fb6-95d910f46cd9|0|-2147483648
e95646ee-ba3a-4978-b2a8-5383f31be2f1|0|-2147483648
e02d0eb3-6c9b-4942-b43c-a752eefc77a8|1630525956184|2147483647
Any ideas how to make it work with multiple and()? If I try to remove the second and() and keep the third one everything works as expected.
After deep investigations I found several problems in my code:
.and() should be called at the end of the "child" condition and not at the "parent" level.
For the conditions like this
val condition1 = Expression.property("type").equalTo(Expression.string(DOC_TYPE))
val condition2 = Expression.property("rating").lessThan(Expression.intValue(1))
val condition3 = Expression.property("timestamp")).lessThanOrEqualTo (Expression.longValue(1))
The correct way is
.where(condition1.and(
condition2.and(
condition3.and(
...
)
)
)
but NOT like I've tried
.where(condition1.and(condition2)
.and(condition3)
.and(...)
)
For the creation of the object I used a code that converts an object to Map<String, Any> before saving to couchbase. Everything seemed to be OK till I realized that Long was converted to Double.
The last point, I have much complicated queries and inside one of them I accidentally used .add() instead of .and(). No comments.
Hope this will help to somebody to save some time.
I would expect that the query would be as you did originally:
.where(condition1.and(condition2)
.and(condition3)
.and(...))
I think there is an additional parenthesis here that seems to be wrong:
.and(Expression.property("timestamp"))
I'm working on using a collectionGroup query and trying to pass it to a Recyclerview but it seems to always be coming up empty.
Firstly, my understanding is that collectionGroups used not to be so great but now I hear it's fixed and it allows a query to grab all documents under a collectionGroup name.
The query I show below doesn't grab anything and I can't figure out why. From the explanation in the documentation, it should be able to grab all bookPendingRequests items across all books(the parent Items) that have an owner of whoever is logged in.
String mAuthUser = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
the line above allows me to grab the logged in username
Query query = firestoreDB.collectionGroup("bookPendingRequests").whereEqualTo("mOwner", mAuthUser)
This line above is what i imagine should work.
code
FirestoreRecyclerOptions<BookRequestModel> options = new FirestoreRecyclerOptions.Builder<BookRequestModel>()
.setQuery(query, BookRequestModel.class)
.build();
mBookRequestsAdapter = new BookRequestsAdapter(options);
RecyclerView bookRequestListRecyclerView = findViewById(R.id.bookRequestListRecyclerViewId);
bookRequestListRecyclerView.setHasFixedSize(true);
bookRequestListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
bookRequestListRecyclerView.setAdapter(mBookRequestsAdapter);
here's an image of what it looks link in firebase:
here's an image of my index for the collectionGroup
Right now I'm just trying to get the query to actually grab the "bookPendingRequests".
Any help or guidance is appreciated.
I have one realm list and i want to sort the list alphabetically.
Collections.sort(contacts, new java.util.Comparator<Contacts>() {
#Override
public int compare(Contacts l1, Contacts l2) {
String s1 = l1.getName();
String s2 = l2.getName();
return s1.compareToIgnoreCase(s2);
}
});
But this logic not woking i am posting crash report below, please kindly go through it.
java.lang.UnsupportedOperationException: Replacing and element is not supported.
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:826
at io.realm.RealmResults$RealmResultsListIterator.set(RealmResults.java:757)at java.util.Collections.sort(Collections.java:1909)
Please kindly go through my post and suggest me some solution.
Sorting in Realm is pretty straight forward.
Here is an example:
Let's assume you want to sort the contact list by name, you should sort it when your querying the results, you will get the results already sorted for you.
There are multiple ways to achieve this
Example:
1) Simple and Recommended way:
// for sorting ascending
RealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name");
// sort in descending order
RealmResults<Contacts> result = realm.where(Contacts.class).findAllSorted("name", Sort.DESCENDING);
Updated since realm 5.0.0
1) Simple and Recommended way:
// for sorting ascending, Note that the Sort.ASCENDING value is the default if you don't specify the order
RealmResults<Contacts> result = realm.where(Contacts.class).sort("name").findAll();
// sort in descending order
RealmResults<Contacts> result = realm.where(Contacts.class).sort("name", Sort. DESCENDING).findAll();
2) for unsorted results
If you are getting unsorted results you can sort them anywhere this way.
RealmResults<Contacts> result = realm.where(Contacts.class).findAll();
result = result.sort("name"); // for sorting ascending
// and if you want to sort in descending order
result = result.sort("name", Sort.DESCENDING);
Have a look here you will find very detailed examples about Realm querying, sorting and other useful usage.
Technically you should use the following:
RealmResults<Contacts> result = realm.where(Contacts.class)
.findAllSorted("name", Sort.DESCENDING);
It is recommended over findAll().sort().
Use this to get the sorting in SORT_ORDER_ASCENDING or SORT_ORDER_DESCENDING
public void sort(java.lang.String[] fieldNames, boolean[] sortAscending)
Check the API reference Reference 1 or Reference 2
I have a small firebase database with a list. How can I get the last inserted value of the list?
The elements of the list have as key a date string, example:
2016_05_29 --> data
2016_05_30 --> data
2016_05_31
2016_06_01
2016_06_02
2016_06_03
2016_06_10
2016_06_11
2016_06_12
2016_06_13
2016_06_14
2016_06_15
2016_06_16
2016_06_17
2016_06_18
2016_06_19 //returned value
2016_06_20
2016_06_21
2016_06_22
2016_06_23 //expected value
I am try to get the last value of this list, so 2016_06_23 but for some reason it returns this 2016_06_19 whatever key/order system I use:
Query dateMaxRef = ref.orderByKey().limitToLast(1); //this returns always 2016_06_19 instead of 2016_06_23
dateMaxRef.addListenerForSingleValueEvent(new ValueEventListener()
....
Any idea?
I faced the same issue and for me the reason was because the query was not using the latest data from firebase and instead relying on internal cache. Using .keepSynced(true) on the query fixed it for me. Below is the sample code -
Query causeListPath = mFirebase.child(PATH_CAUSE_LIST).child(SELECTED_CITY)
.child(SELECTED_COURT_CODE).limitToLast(1);
// If user wants un-cached data, force sync
if (!useCache) causeListPath.keepSynced(true);
causeListPath.addChildEventListener(new ChildEventListener() {
...
});
In my android project i am working on adding a pull to refresh, Since there is nothing mentioned in the document,where i can add pull to refresh directly i have used android SwipeRefreshLayout and developed a pull to refresh functionality. For that to success i need to get latest data set onRefresh() method. So i have saved the last shown ParseObject "createdAt" time as getLastPostDate() and tried to query latest data from last time up to now every time user pulls to refresh as like below query.
query.whereGreaterThanOrEqualTo("createdAt", getLastPostDate());
postList = query.find();
But for some reason i can't query from "createdAt" or "updatedAt" value. Help is appreciated.
EDIT
#JayDev here how i did it.
final ParseQuery<Post> query = Post.getQuery();
query.orderByDescending("createdAt");
postList = query.find(); // getting all the posts
setLastPostDate(postList.get(0).getCreatedAt()); // set the last post date
since posts are in descending order , get i can get the last post from 0 element. (This works!!)
on refresh i use the above code, to get latest posts posted after that date. Please guide me if there is another way to