Firebase Query - how to order by a separate field? - android

I'm working with an Android App that functions as an instant messaging service, and I'm at the point of pulling the message data through into a RecyclerView. I have my Firebase Query object returning all the messages that match the id of the chat that has been loaded, this is done like so:
Query qChatMessages = mDbRefMessages
.orderByChild("messageChat")
.equalTo(mChatId);
So far so good, and this is returning the collection of messages that I expect. The problem is now that, upon passing them to the RecyclerView to be displayed, they come out in the inverse order of how you would typically expect an instant messenger to display, so the messages are actually getting older as you scroll down the chat.
My message nodes in the database all have a messageTimestamp field associated with them, so this is what I would want to sort the data by. The problem is that I don't seem to be able to find a way of ordering the data by any field other than the one that I'm querying on, or getting the results back from Firebase and subsequently ordering them.
Does anyone know how I can work around this, or if there's some Firebase capabilities I'm not aware of?
Thanks in advance,
Mark

The easiest way is to store an extra piece of data in your message nodes which is the epoch time multiplied by -1: this way you can sort on this field and the query will return the right order.
See this post on how to get the epoch time: how to get the number of seconds passed since 1970 for a date value?
However, note that with your current data structure, you will encounter a problem: you will need to sort on this new data (e.g. with .orderByChild("messageCreationTime")) AND filter for a given mChatId (e.g. with equalTo(mChatId)), which is not possible.
So, you would have to re-structure your database (if this is possible) like this:
- messages
- mChatId
- messageUniqueID <- most probably auto-generated by Firebase
- messageTitle: ....
- messageCreationTime: -1525857044
And you would query by:
Query qChatMessages = databaseReference.child("messages").child(mChatId)
.orderByChild("messageCreationTime");

Related

How to query "nearby" & "latest" in firestore with limit in Android?

I have one Android project where I need to query nearby items & these items should be sorted by time.
Basically, I need docs that are in 100KM. Sorted by time (Field).
So I have checked Firestore docs for this & I got solution (Add geoHash to docs & then query them by geoHasBounds) But there is an issue what if there are 1k docs in 100km then it will load all which is not good, so how can I limit those different queries & gets only 25-30 docs then next 25-30 docs ??
In short, this is what I need-
How can I query the latest 25 docs in 100KM radius & when the user scroll down the next 25 docs?
this is my code of query-
List<GeoQueryBounds> bounds = GeoFireUtils.getGeoHashQueryBounds(center, radiusInM);
final List<Task<QuerySnapshot>> tasks = new ArrayList<>();
for (GeoQueryBounds b : bounds) {
Query newQuery = itemQuery.orderBy("geoHash").startAt(b.startHash).endAt(b.endHash);
tasks.add(newQuery.get());
}
// Collect all the query results together into a single list
Tasks.whenAllComplete(tasks).........
What you are looking for is called pagination. I have answered a question here on Stackoverflow, where I have explained a recommended way in which you can paginate queries by combining query cursors with the "limit() method". I also recommend you take a look at this video for a better understanding.
If you are willing to try Paging 3 library, please see below an article that will help you achieve that.
How to paginate Firestore using Paging 3 on Android?
Edit:
The Tasks.whenAllComplete() method:
Returns a Task with a list of Tasks that completes successfully when all of the specified Tasks complete.
So you can then simply convert each object to a type of object that you need and paginate that list accordingly. Unfortunately, this implies getting all the objects in the first place. Otherwise, you can divide those queries into separate queries and treat them accordingly, by using separate paginantion.

Insert a timestamp of data insertion into database

I want to add a timestamp of a data entry creation, example:
myRef.child("uid").setValue(data);
//add timestamp to the same path myRef.child("uid").setValue(<timestamp here>)
What would be the best timestamp, so that it will be independent of any time zone? (For example if a user's phone clock is set to the wrong time)
I did see this article from Firebae docs: Timestamp, but can't figure how to use it.
Use the value placeholder firebase.database.ServerValue.TIMESTAMP to update a value with the current clock time on the server at the time of the write, as seen by the server. It's a token value that means nothing on the client but has a special meaning on the server when it's written.
inside Firebase Functions transform the timestamp like so:
timestampObj.toDate()
timestampObj.toMillis().toString()
documentation here https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp

value parameter not displayed

i've logged a firebase event using the code below in android (a long time ago).
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle params = new Bundle();
params.putString(FirebaseAnalytics.Param.VALUE, String.valueOf(subjectvalue));
params.putString(FirebaseAnalytics.Param.CURRENCY, "IRR");
mFirebaseAnalytics.logEvent("Calculate_Cost_of_Hearing", params);
as you can see in this image the events are being logged and sent to firebase and shown separately but the value indicator still shows zero.
should i change my code in order to make it show the values or should i play with the options ? and my ultimate goal is to know the average values not just the SUM.
I am pretty sure that Value displays 0 because the parameter is bundled as a String. If you use params.putDouble() or putLong() instead of putString() the value should accumulate in the Firebase console.
You will not be able to display the average value per user in the event view since it shows only the accumulated value. If you want to work with the data you will have to connect your Firebase instance to BigQuery, pretty much.
Perhaps you could get the Value included in the "revenue per user" - metric on the Dashboard if you make the event count as revenue, but I have no experience doing that.

How to search in Firestore using multiple fields of documents for android?

I'm using a Firebase Firestore for android to store data. I tried to search data from documents.
My Firestore structure is:
Collection (Products) - Document (Auto Generated ID) - Field (NumberOfPeople,OfferStartDate,OfferEndDate,OfferPrice,Location)
I wrote query for search data on those fields.
CollectionReference collectionOfProducts = db.collection("Products");
collectionOfProducts
.whereEqualTo("Location", location)
.whereGreaterThanOrEqualTo("OfferPrice", offerPrice)
.whereLessThanOrEqualTo("OfferPrice", offerPrice)
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
.get()
I want search result like this: An offer which is between start date and end date, where offer price is greater than equal or less than equal on give price range. This query is not working in android studio.
How to do this in firestore firebase?
According to the official documentation regarding Cloud Firestore queries, please note that there some query limitations:
In a compound query, range (<, <=, >, >=) and not equals (!=, not-in) comparisons must all filter on the same field.
So a Query object that contains a call to both methods:
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereLessThanOrEqualTo("OfferEndDate", date)
Is actually not possible, as "OfferStartDate" and "OfferEndDate" are different properties.
The best solution I can think of is to use only one of these method calls and do the other filtering on the client.
Another possible solution might be to use denormalization and duplicate the data
in certain intervals. In this way, you'll always know the time periods and you'll be able to create the corresponding queries.
To the best of my knowledge, Firestore only lets you use where<Greater/Less>ThanOrEqualTo() and where<Greater/Less>Than() a single field and all other filter operations on other fields can only be whereEqualTo().
Some workarounds for your specific case include -
1) Modifying your query to
collectionOfProducts
.whereGreaterThanOrEqualTo("OfferStartDate", date)
.whereEqualTo("Location", location)
.get()
And then performing the subsequent filtering on the result in your app code.
Alternately, you can perform your filter on "OfferPrice" and "Location" in your query and the remaining filters can be applied to the query result.
2) You can use firebase functions or other server code to write logic that performs customized filtering and fetch the result that way.
i was having same issue with this, but i found a work around that takes sometime to write.
lets say you want to search for a particular keyword(in this case the value of a field inside a document), and you want firebase to search multiple field instead of just looking for 1 particular field.
this is what you want to do.
const searchTerm = document.createElement('input')
db.collection('collection').where('field1', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === '0'){
db.collection('collection').where('field2', '==', `${searchTerm.value}`)
.get()
.then((snapshot) => {
if(snapshot.size === 0) {
db.collection......and repeat
}
})
}
})
in summary, the above code is basically telling js to search for the term again with a different field if the result of the previous query is 0. I know this solution might not be able to work if we have a large quantity of fields. But for folks out there that are working with small number fields, this solution might be able to help.
I really do hope firestore one day would allow such feature, but here is the code it worked fine for me.
the problem I have now is to allow search input to be able to search without have me to complete the word. I do currently have an idea how this would be, but just need some time to put together.

Firebase - How to order items?

I'm trying to make a very simple list-based android app.
Is there a easy way to order objects and sort them by date?
My goal is to show the last added item on top of the list.
I've already tried with a client-side solution but it's not efficient.
At the moment i'm using this json data model:
{
id:"",
name:"",
body:"",
date:"date here"
}
Does anyone have and idea on how to solve this?
You must must use orderedByChild by the key of the date you'd like to order the children by. You can then observe the Value or ChildAdded event type of this query to retrieve the children in ascending order of date. To have the most recent first, you must reverse the objects manually client-side. Otherwise, you could prepend a - symbol to all the dates and handle it client side.

Categories

Resources