How to change Firestore query depending on user selection? [duplicate] - android

I want to query my Workout Collection for the latest workout from a routine. Meaning I query with whereEqualTo my routineKey, order it by the Started TimeStamp in descending order and then limit to 1 and then take the this 1st Key/Id of the Workout.
However this does not work. whereEqualTo and orderBy work separately but not combined. What am I doing wrong?
fm.getColRefWorkout().whereEqualTo("routineKey", routineKey).orderBy("startTimeStamp", Query.Direction.DESCENDING).limit(1).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot documentSnapshots) {
workoutKey = documentSnapshots.getDocuments().get(0).getId();
//To stuff with this workoutKey
}
});

This query will not work unless you create an index for it. This can be done, by creating it manually in your Firebase Console or if you are using Android Studio, you'll find in your logcat a message that sounds like this:
FAILED_PRECONDITION: The query requires an index. You can create it here: ...
You can simply click on that link or copy and paste the URL into a web browser and your index will be created automatically.

Related

Firebase Firestore OR query (Android Studio)

I've been trying to find a query for almost 2 days now
I want to search id (current user id) from the document 4 fields (customer1,customer2,customer3,customer4)
Here is the firestore document picture
tried this query
final Query userQuery = collectionReference
.whereEqualTo("customer1",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer2",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer3",firebaseAuth.getInstance().getCurrentUser().getUid())
.whereEqualTo("customer4",firebaseAuth.getInstance().getCurrentUser().getUid());
but this only shows up if the current ID is present in all 4. Is there any easier way to do this.
You can do that by using a field that is an array containing the uids you want to test, and then applying array-contains on it. In your case:
In your case:
customer: [customer1, customer2, customer3, customer4]
collectionReference
.where("customer ", "array-contains", firebaseAuth.getInstance().getCurrentUser().getUid())
Firestore does not support logical OR queries among mulitple fields. So, what you're trying to do is not possible with a single query using the database structure you have now. You would have to perform multiple queries and merge the results in the client.
If you want to be able to use a single query, you will have to change your database. One option is to put all the customers into a single array field and use an array-contains query to find a customer in that field.

Do I need an AsyncTask to Query a row in my Android Room Database?

I am doing a map activity,
on marker click, I would display the information on a textview.
The information is saved in android room database because I need the data to persist.
I want to query only a row with the name of the column, marker tag
I have searched many ways to query a row, but none of them is specific to my questions.
Yes, reading and writing to Room database must be asynchronous. So you must run your queries in:
AsyncTask.execute(new Runnable()
{
#Override
public void run()
{
// run your queries here!
}
});
Good luck.

How do I get data from a firebase realtime database and change one text field to represent that specific record?

This is my first post here so sorry for any confusion!
I recently started using Flutter and I'm new to Firebase too.
I'm using a realtime database as the backend for my app, and I've got a hierarchy that looks like:
What I want to do is lookup a specific user by their id, fetch their information (gender and name in this case) and then set a widget (in this case a text widget) to use that value.
How can this be accomplished?
I've searched through a lot of StackOverflow questions about this, and all of them use FutureBuilders or DataSnapshots and I can't quite work out how to go about sorting them out so they work.
All of the tutorials online also don't get info from a specific user and instead query the entirety of the database.
You can do the following:
db = FirebaseDatabase.instance.reference().child("Users");
db.orderByKey().equalTo(Id).once().then((DataSnapshot snapshot){
Map<dynamic, dynamic> values = snapshot.value;
values.forEach((key,values) {
print(values["name"]);
});
});
First, you get an instance to the node User, and then using orderByKey() you can search the user by the id, and retrieve the name and gender.
Check the link following for more information:
https://github.com/flutter/plugins/blob/master/packages/firebase_database/lib/src/query.dart#L183

How to order firebase data from the latest

Firebase by default orders data from the earliest and I need it to be ordered from the latest.
I am using timestamp to do so and doesn't seem to be working.
private void filldata() {
mDatabase.child("Data").orderByChild("timestamp").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
System.out.println("snapshot:" + snapshot.toString());
}
}
You no need to use orderByChild() here in your case because firebase itself generate unique key which is based on a timestamp, so you can simply use orderByKey() in your query and you will get your data in latest order.
The unique key is based on a timestamp, so list items will
automatically be ordered chronologically. Because Firebase generates a
unique key for each blog post, no write conflicts will occur if
multiple users add a post at the same time.
You can find more here
I'll suggest to use
mDatabase.child("Data").orderByKey().limitToLast(no_of_items_you_want)
This will give you list of latest data
Also to get value from snapshot use
snapshot.getValue(String.class);
Since orderByChild() only sort data in ascending order, you should store an extra data item in your child node whith the value timestamp*(-1) and then sort (order) on this data item.
Your code is correct. The commonly suggested way to order will be by using a negative timestamp.
However I have noticed previously that firebase does order your results by timestamp, as you currently wish for it to do. When the device receives the results it reorders the results by arrival (suspicion).
To test this, try limit your results by using the .limitToLast(n) function, you will realize that while firebase will return the last 10 (in order of timestamp) results to you, these results will not be ordered by timestamp.
Therefore, the best solution will be to store the firebase results in a list and reorder the list using a sorting tool like a comparator

Querying on Firebase Database with large data set is very very slow

I use Firebase database on my Android app. Normally, it works fine. But when the database is getting larger, the query performance is getting worse. I added about 5k record on database (under "elk" and "su" nodes), then I queried on database (on "cut" and "user" nodes) but all the queries are very very slow. I defined data index on database rules but it did not work. How can I solve that problem?
Here are my queries :
// query to get the zones followed by user
FirebaseDatabase.getInstance()
.getReference()
.child("user")
.child(userID)
.child("zones");
// query to get cuts on a zone
FirebaseDatabase.getInstance()
.getReference()
.child("cut")
.child(cutType)
.orderByChild("zoneID")
.equalTo(zoneID);
If you want to continue expanding the best thing to do would be to duplicate your data in a zone reference where it knows which elk/su are a part of it. Something like this:
{
zones: {
elk: {
"istan-besik": {
"-KSp)bL5....": true,
...: true
}
}
}
}
That way when you want to search for all you would just do:
...child('zones').child(zoneId).child(cutType)
And then loop through those to go get each elk/su directly

Categories

Resources