Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore timestamp getting null

I'm using firestore in my android project, everything working fine.But Yesterday an issue occurred on getting timestamp value from document snapshot.

if (documentChange.getType() == DocumentChange.Type.ADDED) { 
  Map<String, Object> stringObjectMap = documentChange.getDocument().getData(); 
  Date date = (Date) stringObjectMap.get("timestamp"); }

This is one of my Collection Document.

 id : "25",
 message : "This is my message",
 timestamp : December 11, 2017 at 10:39:12 PM UTC+5, \\This is Firebase FieldValue.serverTimestamp()
 username : "Temp"

I get everything from the document except for timestamp.

like image 796
Ahsan Saeed Avatar asked Dec 12 '17 11:12

Ahsan Saeed


Video Answer


1 Answers

If you are seeing this ADDED event with a null timestamp after writing from the same client, this is the expected behavior.

When you write with server timestamps you will get two events:

  1. An initial event confirming the document write in the local cache. At this point the timestamp is null because the server has not set it yet.
  2. A second event where the timestamp has been set by the server and the client has observed the change.

We are working on an API to make this behavior configurable, but right now you need to handle this case.


Edit You can now control this behavior.

DocumentSnapshot snap = ...

// One of ESTIMATE, NONE, or PREVIOUS
DocumentSnapshot.ServerTimestampBehavior behavior = ...

Date date = snap.getDate("fieldName", behavior);

The previous behavior (returning null when not known) is equivalent to NONE in the new API. For more information, see the JavaDoc: https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/DocumentSnapshot.ServerTimestampBehavior

like image 127
Sam Stern Avatar answered Sep 17 '22 22:09

Sam Stern