0

I am trying to save a list of data to the Firebase Realtime Database in Kotlin. But when I try to save the order gets shuffled as below.

enter image description here

This is my code. Here the locationlist is the array that contains the list of locations that I want to save in the same order as it is. But when I try to save the after the first element, 10th element is showed. And the pattern continues like that.

 ref.child(pk).child("location${count+1}").setValue(locationList).addOnCompleteListener {

                Toast.makeText(requireContext() ,"success$pk", Toast.LENGTH_SHORT).show()


            }
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
user16493824
  • 57
  • 1
  • 12

1 Answers1

1

If you are looking for an ascending order in code, the following lines will keep the order that exist in the array. Assuming you have a property "name" within each object, please try the following code:

    val rootRef = FirebaseDatabase.getInstance().reference
    val locationRef = rootRef.child("location2")
    locationRef.get().addOnCompleteListener { task ->
        if (task.isSuccessful) {
            for (ds in task.result.children) {
                val name = ds.child("name").getValue(String::class.java)
                Log.d(TAG, name!!)
            }
        } else {
            Log.d(TAG, task.exception!!.message!!) //Don't ignore potential errors!
        }
    }
}

If you want to change the order in the Firebase Console, please note that this is not possible. Check for a workaround in my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193