0

I want to create a master list in Firebase Realtime database using java in which the keys should be auto generated as well as consecutive numbers (0,1,2...). Something like

enter image description here

I will add the child data whenever user feeds. but i do not precisely know the what the last id stored. for example, if i had 3 records (IDs: 0,1,2) already, and user feeds me one more, I have to set the new data with the id '3' which i do not exactly know.

Is there any way to automatically add data with consecutive numbers?

As an alternative I'm using .push() method which gives me some random id which i dont actually like.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jeyasurya U R
  • 666
  • 1
  • 4
  • 8
  • 1
    Why would you like to have consecutive numbers? How about deleting a child? If you delete "child2", would you like "child3" to become "child2"? – Alex Mamo Apr 19 '23 at 10:06
  • 2
    Refer this well written doc: https://firebase.google.com/docs/database/admin/save-data#section-push – Shri Hari L Apr 19 '23 at 10:42
  • 1
    As the others have commented, using incremental sequential numeric keys is an anti-pattern in Firebase. For more on that, see [Best Practices: Arrays in Firebase](https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html). That said, if you insist on implementing this, see: https://stackoverflow.com/questions/67205169/how-can-i-make-the-count-keep-increasing-without-the-count-starting-0-again/67205362#67205362 and https://stackoverflow.com/questions/39519021/how-to-create-auto-incremented-key-in-firebase – Frank van Puffelen Apr 19 '23 at 13:21

0 Answers0