Firebase Getting Data in Order

Firebase getting data in order

Solution: After very extensive searching and attempting, the problem still persisted that once the snapshot was converted to a snapVal (snapshot.value), the order often rearranged. My (working) solution:

for child in snapshot.children {
let child = child as! FIRDataSnapshot
if let childVal = child.value as? [String: AnyObject] {
let childMessage = childVal["MESSAGE"] as! String
// more code for each child. This child might be a post of a sort, which you can access properties of in a way like I did in the line above
}
}

Process:

  1. Loop through each child in snapshot

  2. Convert the child to a FIRDataSnapshot so it is not an element

  3. Get the value of the particular child to access properties from

  4. Add in the respective code for the child following NSDictionary principles.

Why this solution is solid

Receiving snapshots in the proper order is very simple. The issue I faced was getting data in the correct order when I got the snapshot.value. This solution fixes that because the values of each child are only accessed when looping through the children of snapshot, which is sorted. This leaves the order of children still in the control of the snapshot.

I also like the snapshot.value approach by using [String: AnyObject] because it is very close to the old functionality of Firebase implementation in Swift: Simple and very clean. I actually think that using NSDictionary in this way is really a way to save time in the long run because it is not verbose in any way.

Guaranteed order of fetched data from Firebase Realtime Database

What is the order of data when I fetch from my Firebase Realtime Database without using any orderBy methods?

If you are looking to have your elements ordered even if you don't use a call to orderBy(), then you should use the pushed IDs provided by the DatabaseReference#push() method. These pushed IDs aren't actually timestamps but they contain a time component. As Michael Lehenbauer mentioned in this blog article:

Push IDs are string identifiers that are generated client-side. They are a combination of a timestamp and some random bits. The timestamp ensures they are ordered chronologically, and the random bits ensure that each ID is unique, even if thousands of people are creating push IDs at the same time.

And to answer your second question:

If I use the get(), is it always 100% guaranteed that the data I will get is sorted from oldest to the newest or will it be in lexicographical order?

It doesn't matter if you add a ValueEventListener or ChildEventListener or even if you call Query#get(), the results will be ordered in the same way.

However, if you need to explicitly have an order according to a time component, then you should add a property of type "timestamp", as explained in my answer from the following post:

  • How to save the current date/time when I add new value to Firebase Realtime Database

If you want to reverse the order please check the following answer:

  • Sort data to RecyclerView based on latest date from Firebase

How to get in order data from two different children in Firebase Realtime Database?

I want to get videos and photos together in the order they were taken. Like a phone gallery.

You can perform a Firebase Realtime Database query only on a single node. You cannot get data across multiple nodes using a Query. If you want to get the "photos", as well as the "videos" in a single go, then both should exist within the same node. So you should create another node called "photosAndVideos" where you should add all the data. This practice is called denormalization and is a common practice when it comes to Firebase. For a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database.

Once you have all data under a single node, you can then perform the desired query according to a timestamp. Please see my answer from the following post:

  • How to save the current date/time when I add new value to Firebase Realtime Database

To see how to add a timestamp property to your object. By default Firebase orders the results ascending. However, if you need a descending order, please see my answer from the following post:

  • How to arrange firebase database data in ascending or descending order?

Edit:

You have to check each object from the results an instance of which class is. So when you read the data, you cannot only cast the value. You'll have to read each object and request the correct class in the call to getValue().

Firebase getting data in letter order

You can try

let dic = snapshot.value as! [String:String]
let sortedKeys = Array(dic.keys).sorted(by:<)
self.tableRowss = sortedKeys.map { dic[$0]! }
self.myTableView.reloadData()

Firebase - getting list of data in order (Last data first)

I would suggest adding a time stamp to you nodes which will guarantee the order. You would then also add a negative time stamp as well which would enable descending sort

messages
msg_0
msg: "What's up"
timestamp: 20190927013000
neg_timestamp: -20190927013000
msg_1
msg: "Hi"
timestamp: 20190927020000
neg_timestamp: -20190927020000

Then you can query but timestampt for ascending and neg_timesstamp for descending and will be guarateeed order.

The nodes are in random order because you're reading them as a Dictionary which are unordered sets of key: value pairs.

let currentUserChatList = snapshot.value as? NSDictionary

If you want them IN order then do this

let currentUserChatList = snapshot.children.allObjects as! [DataSnapshot]

which will maintain their order, and you can iterate over them with a for loop as in your question. Each child will be a DataSnapshot as well so you can access the child nodes with

let child in currentUserChatList {
let msg = child.childSnapshot(forPath: "msg").value as? String ?? "No Msg"
}

Flutter + Firebase. Sorting data in chronological order

Yes you need a createdAt timestamp field and use it like

Firestore.instance
.collection("users")
.orderBy('createdAt', descending: true or false).getDocuments()

And you can store createdAt on flutter side with Timestamp (Its included in cloud_firestore), and you can get current timestamp with Timestamp.now()

How to order data from firebase using timestamp in android in Kotlin

To order the child nodes you'll want to use a query as shown in the documentation on ordering and filtering data:

dref = FirebaseDatabase.getInstance().getReference("Products")
val query = dref.orderByChild("prodTime")

query.addValueEventListener(object : ValueEventListener {
...

How to arrange firebase database data in ascending or descending order?

If you want to order the results of a Firebase database query, you need to use numbers as values and not Strings. If you keep the Strings, as I see in your screenshot, you need to know that the Strings are ordered lexicographically and I'm sure this is not what you are looking for.

The simplest way to order data in ascending or descending order, would be on client side. Firebase can order the results in ascending order by a given property by default. There is no method in Firebase to order in descending order but there a few tweaks that can be made.

If you are using a RecyclerView to display data, the simplest way would be to use the following code:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);

This approch will reverse you the order.

Another approach would be to create your own adapter that extends FirebaseListAdapter and override getItem() method.

Another approach would be to get the data from the database, add it to a Collection, a List would be a good solution and then use Collections.reverse(yourList);.

How to sort Firebase data according to Time Created?

Because of orderByChild("name"), whenever a new Data is inserted in the Database is not according to the Time

When you are using:

.orderByChild("name")

It means that the results that are coming from the database will be ordered according to the values that exist in the "name" property, and not according to a "time".

Instead, it inserts the data in the RecyclerView in a Random Order.

As said above, that's definitely not a random order. If you need to get the results according to the "time" of the addition, then you have two options.

If, for example, the "M38dJdquf4jE" is a pushed key that is provided by the "push()" method, you can use Query's orderBykey() method, which:

Creates a query in which child nodes are ordered by their keys.

You'll get the results ordered because the pushed keys contain a time component.

If those keys are not provided by the "push()" method, to have an order according to a time component, then you should add a property of type "timestamp", as explained in my answer from the following post:

  • How to save the current date/time when I add new value to Firebase Realtime Database

Once you have that new property in place, you can use:

.orderByChild("timestamp")

To have the results ordered ascending. If you need however a descending order, then you can use my answer from the following post:

  • How to arrange firebase database data in ascending or descending order?


Related Topics



Leave a reply



Submit