ServerTimestamp is always null for Firebase Firestore

I am trying to add a timestamp field in an Android client with Firebase Firestore.

According to the documentation :

An annotation used to mark a date field that must be filled in with a server timestamp. If the recorded POJO contains a NULL value for the field annotated by @ServerTimestamp, it will be replaced by the timestamp generated by the server.

But when I try this:

@ServerTimestamp
Date serverTime = null; // I tried both java.util.Date and java.sql.Date

//...

Map<String, Object> msg = new HashMap<>();
// ... more data
msg.put("timestamp", serverTime);

This field is always in the Cloud Firestore database null.

+6
source share
3 answers

Cloud Firestore. , Date . :

import java.util.Date;

public class YourModelClass {
    @ServerTimestamp
    private Date date;

    YourModelClass() {}

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }
}

YourModelClass . Firebase date ServerTimestamp (. ) .

FieldValue.serverTimestamp() :

Map<String, Object> map = new HashMap<>();
map.put("date", FieldValue.serverTimestamp());
docRef.update(map).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}
+8

FieldValue.serverTimestamp()

Map<String, Object> msg = new HashMap<>();
msg.put("timestamp", FieldValue.serverTimestamp());
+4

I have a similar problem and I found this in my catlog and solved my problem

firebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
                .setTimestampsInSnapshotsEnabled(true)
                .build();
firebaseFirestore.setFirestoreSettings(settings);
0
source

Source: https://habr.com/ru/post/1692805/


All Articles