Firebase: Get reference to first item/element - android

I'm trying to get a reference to the fist item in a firebase "Array"
In my case it would be "ElmmycgjS1Nvq.../albums/-IrdMMds"
But I'm not sure how to contsturct the query:
dbRef.child("ElmmycgjS.../albums").???.child("name"); // = "Brothers in Arms"
Where ??? should be something like getFirst().
Suppose I don't know the Id of the first Album beforehand (-IrdMMds). I just need to get the first one. I've tried limitToFirst(1).getRef() but this didn't help.

You'll want a query that listens for the first child:
Query first = dbRef.child("ElmmycgjS.../albums").limitToFirst(1);
And then attach a listener to that query.
When you execute a query against the Firebase Database, there will potentially be multiple results. So the result of the query will be a list of those results. Even if there is only a single result, the it will be a list of one result.

Related

Where condition in my query not filtering the records properly

Where condition in my query not filtering the records properly. I have attached my query and results in the picture. The records must show only the taskNum="88" but additionally it's also showing 89. My need is to get the record where taskNum="88" and Tranlineno=1 or Null. Help me please what's wrong with the query.
You need to use proper parenthesis to properly format the query.
SELECT *
FROM picktaskdetail
WHERE taskNum="88" AND (Tranlineno="1" OR wlotno is NULL) AND ITEM = "0101010601BR"
Add proper parenthesis for the condition you write in query.
Your conditions are:-
taskNum="88"
Tranlineno=1 or Null
Now, this can be Get the result that matches condition 1 & condition 2.
Now your condition 2 is an OR condition so that needs to be handled separately using parenthesis.
See the below-mentioned query implementation:-
SELECT *
FROM picktaskdetail
WHERE taskNum="88"
AND (Tranlineno="1" OR wlotno is NULL)
AND ITEM = "0101010601BR"

Is it possible to use Where In with a Collection Group query in Firestore?

In my database:
-Users(Top level collection):
---user1(doc):
----------pets(sub collection):
--------------pet1(doc)
--------------pet2(doc)
---user2(doc):
----------pets(sub collection):
--------------pet3(doc)
--------------pet4(doc)
If i have a List of ids: list("pet2", "pet3", "pet4)
Is there a way to do something like this and get a back a List of DocumentsSnapshots?
firestore.collectionGruop("pets")whereIn(FieldPath.documentId(), list)
It works with a root collection but i dont know if this is possible with a collection group
A collection group query is the only place where a filter on FieldPath.documentId() does not work the way you expect. That's because of some details about the way that this token actually works. If you try to this anyway, you will get an error like this:
Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, but 'x' is not because it has an odd number of segments.
If you want to do a filter on document IDs in a collection group query, you will need to store the ID of the document as the value of a field in each document. If you use the field called "id", then you can filter on that field like this:
firestore
.collectionGruop("pets")
.whereIn('id', list)
This will give you a different error saying that you need to create an index, and give you a link to do so. After you create that index (it might take some time), you should be good to go.
See also: How to perform collection group query using document ID in Cloud Firestore

How to query Firebase database and not show values based of a boolean value

I am using FirebaseListAdapter in Android to display a list of Orders based off a certain date:
Query orderQuery = ordersRef.orderByChild("dateCreated").startAt(d1.getTime());
My Orders have a completed boolean property
-KsRHO1sLcVxKtVMec3o
completed: false
dateCreated: 1503713136950
I would like to only show not completed items in my list adapter.
the current query above retrieves all orders.
The issue is I don’t know how to query the database correctly to get this to work.
The only idea I have is in the populateView method of the FirebaseListAdapter to check if(!model.isCompleted()){ } and not fill in the textViews associated with the list item.
What way could I achieve my desired result?
in firebase there is not Multi Select or "Multi Query"
so you can orderByChild creating time Or compeleted
So you have to use the Method You mention in your Question
The only idea I have is in the populateView method of the
FirebaseListAdapter to check
if(!model.isCompleted()){ } and not fill in the textViews associated with the list item.
or you have to edit your database Structure
-completed
-KsRHO1sLcVxKtVMec3o
dateCreated: 1503713136950
and
-Notcompleted
-KsRHO1sLcVxKtVMec3o
dateCreated: 1503713136950
like when it`s completed .. remove it from notcompleted Node and
add it in completed node
You can try to use different references for completed and incomplete orders.
Initially when order is placed it will be in the incomplete state and when your order is updated then move the order with key in the complete reference.
Step 1:
Initially when order is getting placed, store the order in a "incomplete" reference like:
-incomplete:{
-anyRandomKeyGeneratedByFirebase:{
"orderTitle":"My First Order"... your order detail goes here
"orderKey":"anyRandomKeyGeneratedByFirebase"
},
.
.
.
}
Above structure will be for incomplete order.
When you know that your order status is completed then you will have to move order into the complete child reference like:
-complete:{
-anyRandomKeyGeneratedByFirebase:{
"orderTitle":"My First Order"... your order detail goes here
"orderKey":"anyRandomKeyGeneratedByFirebase"
},
.
.
.
}
So in this it will solve your problem. Rather than fetching all orders fetch only completed orders from complete reference.
-orders:{
-incompleteOrders:{
},
-completeOrders:{
}
}

Firebase query implementation

If we query data from Firebase on a key for a child node, does it downloads the whole child node and filter data in the application or it downloads the query specific data? i.e. the filtered data
String myUserId = getUid();
Query myTopPostsQuery = databaseReference.child("user-posts").child(myUserId).orderByChild("starCount");
myTopPostsQuery.addChildEventListener(new ChildEventListener() {});
myTopPostsQuery will sort data according to starCount and I will receive data in the addChildEventListener() I want to know that whether this data is being filtered inside my app after receiving or my app downloads only the filtered data from the Firebase.
If you use a filter in your query you will download the query specific data without any operation executed on the client side.
Keep in mind that:
You can only use one order-by method at a time. Calling an order-by method multiple times in the same query throws an error.
You can combine multiple limit or range functions. For example, you can combine the startAt() and endAt() methods to limit the results to a specified range of values.
For any other info take a read here
You get the data already filtered. When you use a query, let say, limitToLast(10) you get only those 10 elements. This is happening also in your case with orderByChild("starCount"). In your SnanpShot will find only those filtered elements. Please visit official doc for more details.
Hope it helps.
Based on the code you pasted here, your query will just retrieve all the posts for the database path user-posts/<id> with an ordered manner which means that there is not filter. But still you will get back all the available posts under the path you are querying. It can be a "semi-filter" as it will find only the posts which include starCount field
The best thing is to filter during your query in order to retrieve back exactly what is needed and not everything as you are doing right now, imagine that this list of posts can be really big so you will have a big issue with performance later.
Read the following section here about sorting & filtering.
https://firebase.google.com/docs/database/admin/retrieve-data#orderbychild
Apart from that consider to add an index in userId field for speeding up your query.

Android parse.com I can't get second user from data base

I have two tables in data base. One is user ad the second is transaction that have pointer to the first user, pointer to the second user and int. When I try make and display list I have error. I want to display all rows that CurrentUser is in first column:
ParseUser cu = ParseUser.getCurrentUser();
query.whereEqualTo("first", cu);
and list it with firstUser, secondUser and int:
from Adapter:
ParseObject taskObject = mTask.get(position);
ParseUser first = taskObject.getParseUser("first");
holder.firsthp.setText(first.getUsername());
ParseUser second = taskObject.getParseUser("second");
holder.secondhp.setText(second.getUsername()); //this line make error
int ile = taskObject.getInt("ile");
holder.taskhp.setText(Integer.toString(ile));
return convertView;
This is how transakcja table looks: http://i.stack.imgur.com/yh83p.png
When I saving transaction (when transaction table is clear, don't have any records) and immediately read it works but when I logout and login it crashes.
And here is entire code for toDoActivity Task Adapter and hplayout:
I had problems with pasting code here so I pasted it on pastebin
http://pastebin.com/2wtQLJXE
I think I know the problem. When you are calling your query on the transaction table, the two User's are Pointers to ParseObjects, or ParseUsers in this case. You need to ensure that these objects are FETCHED as well by the ParseQuery in order to properly access their data. They are ParseObjects with data from another table, Parse does not automatically retrieve them so you must tell Parse to do so when you need that data.
Looking at ParseQuery documentation for Android we find the include method.
public ParseQuery include(String key)
Include nested ParseObjects for the provided key.
You can use dot notation to specify which fields in the included object that are also fetched.
You want to use this to include columns names to Pointers of ParseObjects so the query fetches them at the same time as fetching the rest of the data from the table, in this case your transaction table.
Add this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("transakcja");
query.whereEqualTo("first", cu);
query.addDescendingOrder("createdAt");
query.include("first");
query.include("second");
The reason first is having no null issues, is it is the Pointer to the current ParseUser logged in, which doesn't need to be fetched as it's data is accessible. The second one is not fetched, therefore adding the include to the query SHOULD fix this :). Make sure to also include the column "first" because I'm sure your future ParseQuery's will not always be between the current user and non-current second user

Categories

Resources