0

In my firebase realtime database i have list of integers and the key of these values is integer too when i add new value to the list it doesn't add the new value to the last of this list (firebase sort this list From the smallest to the largest) so how can i forbid this method so the new values are always added to the end of the list without the Firebase arranging them.

this is picture of my list:this is picture of my list

if i add 0 as an example it will be the first value in the list what i want is to be the last value in the list because it's the newest value:enter image description here

Note: i want the values to be unique for example(number 9 should not duplicate) that's why i can't use push to generate new key every time.

2
  • You say it doesn't add the new value to the last of this list and right after that you say as the new values are always added to the end of the list. So are the values added or not to the end of the list? Commented Mar 24, 2021 at 16:04
  • i update the question can u see it now Commented Mar 24, 2021 at 17:31

1 Answer 1

2

Firebase keys are by definition unsorted, but the console shows them in alphabetical/lexicographical order. Since there is no indication of "time" in your current JSON, there is also no way for your own application code to do anything different.

Use Firebase's push() operation, which generates unique, always-incrementing keys. While they may be a bit longer than your current keys, they are by definition chronologically ordered.

So instead of something like this to add the data:

ref.child("9").setValue(9);

Use this:

ref.push().setValue(9);

Update

Since you indicate that you want the numbers to be unique, you can use them as the key (since there's no way to ensure unique value in Firebase), but then store a timestamp in the value of each node.

ref.child("9").setValue(ServerValue.TIMESTAMP)

The console will still show the keys in lexicographical order, but when accessing the data from the client you can now use orderByValue() to get the items in the order in which they were inserted.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for response... but the values in this list should not duplicate if i use push value 9 for example will added twice to the database which is not what i want
That would be useful to know for others, so I recommend adding this uniqueness requirement to your question too. I added an update to my answer to show an alternative that incorporates that requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.