Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Firestore data by TimeStamp in Ascending order

I am storing Ideas posted by the application in Firestore. The data is stored in Firestore like this Ideas/{documentID}/IdeaObject. The issue is when I retrieve the data it is not sorted w.r.t time it was posted. The ideas that are retrieved are in according to the id's of their documentID which is automatically create by Firestore. I have used ServerTimestamp in my Model Class and also when I retrieve it, I use the orderBy method with my Firestore reference but still nothing.

Idea.java

public class Idea {     @ServerTimestamp     private Date date;     private String title, idea, timeCommitment, ideaStage, postedBy, website, videoPitch;     private int views, favorites;     private ArrayList<String> lookingFor = new ArrayList<>();     private ArrayList<String> tags = new ArrayList<>();     private String userID;     private String timeStamp;      public Idea() {     }      public Idea(String title, String idea, String timeCommitment, String ideaStage, String postedBy, String website, String videoPitch, int views, int favorites, ArrayList<String> lookingFor, ArrayList<String> tags, String userID, String timeStamp) {         this.title = title;         this.idea = idea;         this.timeCommitment = timeCommitment;         this.ideaStage = ideaStage;         this.postedBy = postedBy;         this.website = website;         this.videoPitch = videoPitch;         this.views = views;         this.favorites = favorites;         this.lookingFor = lookingFor;         this.tags = tags;         this.userID = userID;         this.timeStamp = timeStamp;     } 

Ideas Posting Method

  private void postIdea() {          final String ideaID = UUID.randomUUID().toString();         final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");         Timestamp timestamp = new Timestamp(System.currentTimeMillis());           Idea ideas = new Idea(title, idea, timeCommitment, ideaStage, AppValues.fullName, website, videoPitch, 0, 0, lookingFor, tags, AppValues.userId, "" + timestamp.getTime());          firestoreDb.collection("ideas")                 .document(ideaID)                 .set(ideas)                 .addOnSuccessListener(new OnSuccessListener<Void>() {                     @Override                     public void onSuccess(Void aVoid) {                         postIdeaUser(ideaID);                     }                 })                 .addOnFailureListener(new OnFailureListener() {                     @Override                     public void onFailure(@NonNull Exception e) {                         hideLoadingDialog();                         showToast(e.getMessage());                     }                 });     } 

Retrieving all Ideas by Time

   firestoreDb.collection("ideas")                 .orderBy("timeStamp", Query.Direction.ASCENDING)                 .get()                 .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {                     @Override                     public void onComplete(@NonNull Task<QuerySnapshot> task) {                         if (task.isSuccessful()) {                              ideaArrayList = new ArrayList<>();                             ideaArrayList.clear();                              for (DocumentSnapshot documentSnapshot : task.getResult()) {                                 Idea idea = documentSnapshot.toObject(Idea.class);                                 if (!idea.getUserID().equals(AppValues.userId)) {                                     ideaArrayList.add(idea);                                 }                             }                              callAdapter();                          } else {                             Log.d(TAG, "Error getting documents: ", task.getException());                             progressBar.setVisibility(View.GONE);                             swipeRefresh.setEnabled(true);                             errorText.setVisibility(View.VISIBLE);                         }                     }                 });  

What I want to achieve is retrieve all the ideas and have them ordered ascending by the TimeStamp value.

like image 306
Ebad Ali Avatar asked May 08 '18 01:05

Ebad Ali


People also ask

How do I sort data in firestore database?

You can specify the sort order for your data using orderBy() , and you can limit the number of documents retrieved using limit() . Note: An orderBy() clause also filters for existence of the given field. The result set will not include documents that do not contain the given field.

How do I get most recent documents on firestore?

Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!

Does firestore have timestamp?

firestore. Timestamp. A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.


2 Answers

You cannot use a String (timeStamp) when querying your database instead of a Date (date) and expect to behave as it was a date. So to solve this, please change the following line of code:

firestoreDb.collection("ideas")             .orderBy("timeStamp", Query.Direction.ASCENDING) 

to

firestoreDb.collection("ideas")             .orderBy("date", Query.Direction.ASCENDING) 

To make it work, this kind of query requires an index. To create one, please check my answer from the following post:

  • Firestore whereEqualTo, orderBy and limit(1) not working
like image 89
Alex Mamo Avatar answered Sep 23 '22 21:09

Alex Mamo


In my case, the vanilla version would be,

firestoreDb.collection("ideas")      .orderBy("timestamp", "asc")  firestoreDb.collection("ideas")      .orderBy("timestamp", "desc") 

"ideas" is the name of your collection

"timestamp" is the key or field or column name to be used for sorting.

"asc" or "desc" is the option to be used for the order

like image 21
Vince Banzon Avatar answered Sep 22 '22 21:09

Vince Banzon