0

I'm Working with stock management project and my client want sales of stock in ascending and descending order.

I have Stock structure as below

enter image description here

I want to sort the data as per the sales of the product.

NOTE: There are thousands of products in this database, so downloading and then sorting the data isn't good idea. I believe this will slow down the process.

Pritam Pawade
  • 637
  • 7
  • 21
  • You can follow this Firebase Doc. Based on any key you can order. But to achieve your usecase you have to manually short your list. https://firebase.google.com/docs/database/web/lists-of-data#sort_data – Ankit Aman Aug 24 '19 at 17:14

2 Answers2

6

You can get sorred data in ascending order from firebase using orderByChild function.you will need to create indexes on table . Refer firebase sorting data section https://firebase.google.com/docs/database/android/lists-of-data

// Descending order:

Do this task at client side as you already have sorted list. Use collections inbuilt function to reverse the list Collections.reverse(inputList)

Hope this helps you :)

Ashok Kumar
  • 1,226
  • 1
  • 10
  • 14
  • Thanks for the reply, This article solved my problem 50% :) Using this article I can sort the data in descending order but I want to sort the data in Ascending order as well any Idea how to do it? – Pritam Pawade Aug 24 '19 at 17:17
1

You can't perform a sort operation on the data stored in the database. However, you can retrieve the data in a particular sorted order, example:

Query myStocksQuery = databaseReference.child("stocks")
        .orderByChild("Sold");
myStocksQuery.addChildEventListener(new ChildEventListener() {
    // do your stuff here
});
Yash
  • 3,438
  • 2
  • 17
  • 33
  • I got this, Ashok Kumar already directed me to the solution, but this query displaying data in descending order I want to show the same data in ascending order as well any Idea? – Pritam Pawade Aug 24 '19 at 17:30
  • 2
    Firebase doesn't return it in descending order, you have to do it on client side. – Yash Aug 24 '19 at 17:33
  • 1
    Do this task at client side as you already have sorted list. Use collections inbuilt function to reverse the list Collections.reverse(inputList) – Ashok Kumar Aug 24 '19 at 17:42
  • Yup, I got it, I retrieved the data in descending order (as you suggested) in group of last 100 items, then displayed these records by inverting them. repeated the same till no elements left. Thanks for the help :) – Pritam Pawade Aug 24 '19 at 17:46
  • Oh, thanks. how can I forget that collection will simplify the process... BTW. I'll use collection thanks again :) – Pritam Pawade Aug 24 '19 at 17:48
  • 1
    Yeah, collection is simpler. – Yash Aug 24 '19 at 17:49