Reputation: 31
In my Firestore database I have field index no, datatype is string but he data is number like 1, 2, 3 and so on.
collectionReference
.orderBy("indexNo", Query.Direction.DESCENDING)
the output is ok till 9, after 9 i.e., for 10, 11, 12, the data is displayed 1, 10, 11, 12, 2, 3 and so on.
Pleas guide me to resolve it, as these numbers will decide the arrangement of cardview items in recycler view.
Thanks...
Upvotes: 2
Views: 2996
Reputation: 138824
If the data type of your indexNo
property is of type String and if you want to order the results using Query.Direction.DESCENDING
, the result will be not the expected one because when you order strings, the results are ordered lexicographically. There are two ways in which you can solve this issue. The first one would be to change the data type of your property from String to number, which I personally recommend it.
This is the normal order for numbers:
And this is the normal order for strings:
The second approach would be to modify the data to get the behavior you want. For numbers, you can accomplish that by padding them with zeroes, like in the example below:
Upvotes: 4
Reputation: 31
Better to change data type from string to integer. I did it. Thanks for your support.
Upvotes: 0
Reputation: 962
The ordering is lexicographic since the data-type is string. Think of the numbers as alphabets. 0 = A, 1 = B, 2 = C... When comparing 9 and 10, think of it like comparing the words 'I' and 'BA'. In a dictionary, which would you expect to appear first?
Upvotes: 0