Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

Querying Firebase based on ServerValue.TIMESTAMP


I have a FireBase back end that has a time stamp like so... there are many of these nodes that are objects that have been pushed.

DB set up

each node has a time stamp set with ServerValue.TIMESTAMP.

in data model class setting server time

private HashMap<String, Object> timestampCreated;

//set time stamp in constructor when new obj is created
public DataModel(...){
 // TIME STAMP
    HashMap<String, Object> timestampCreatedObj = new HashMap<String, Object>();
    timestampCreatedObj.put("date", ServerValue.TIMESTAMP);
    this.timestampCreated = timestampCreatedObj;
}

//getting timestamp

   public HashMap<String, Object> getTimestampCreated(){
    return timestampCreated;
}

@Exclude
public long getTimestampCreatedLong(){
    return (long)timestampCreated.get("date");
}

The above all works fine for insertion in DB and i can retrieve the time.

in another class i want to set a query on a FirebaseListAdapter setting the query lets say for showing items in last 5 days.

  long daysInpast= new Date().getTime() - TimeUnit.MILLISECONDS.convert(5, TimeUnit.DAYS);

Then i set up query

        Query queryDays= mDatabaseQuery.child("timestampCreated").orderByChild("date").endAt(daysInpast);

final FirebaseListAdapter<myData> adapterQuery = new FirebaseListAdapter<myData>
                (getActivity(), myData.class, R.layout.list_item, queryDays) {//do stuff}

Its my query I'm not sure of, my list is returning empty, If i just use my FirebaseListAdapter without the query passing the DB reference my list populates as expected. I suspect its how data is laid out? he fact my times tap is in a subnode is that an issue?

I've tried just using

Query queryDays= mDatabaseQuery.orderByChild("date").endAt(daysInpast);

also but no vail

any help appreciated


Solution

  • You need to run a query on the location above the children that you want returned, which looks to be the root of your database (please don't post pictures with blurred out text, post the actual JSON as text next time).

    If indeed you need the level under the root of your database, you can query for the date with:

    DatabaseReference root = FirebaseDatabase.getInstance().getReference();
    Query query = root.orderByChild("timestampCreated/date").endAt(daysInPast);