Issue
I have read lots of stackoverflow questions related to
ServerValue.TIMESTAMP
but I can't figure out how to use it in my app.
I need to get the timeStamp of the creation of a post. The timeStamp should be added to the same place as with uid , author etc. of the post.
Code snippet which writes the post the firebase database:
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
My Post.java file
@IgnoreExtraProperties
public class Post {
public String uid;
public String author;
public String title;
public String body;
public int starCount = 0;
public Map<String, Boolean> stars = new HashMap<>();
public Long timeStamp;
public Post() {
// Default constructor required for calls to DataSnapshot.getValue(Post.class)
}
public Post(String uid, String author, String title, String body) {
this.uid = uid;
this.author = author;
this.title = title;
this.body = body;
}
// [START post_to_map]
@Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("uid", uid);
result.put("author", author);
result.put("title", title);
result.put("body", body);
result.put("starCount", starCount);
result.put("stars", stars);
return result;
}
// [END post_to_map]
}
How should I use
ServerValue.TIMESTAMP
in my code to get the time of creation of post.
Solution
ServerValue.TIMESTAMP is simply a placeholder value. When the Firebase server processes an update request and finds ServerValue.TIMESTAMP
as a value, it replaces it with the current server clock.
In your writeNewPost()
method you could add a line to set the creation time:
Map<String, Object> postValues = post.toMap();
postValues.put("timeStamp", ServerValue.TIMESTAMP);
If you use Post.toMap()
only to create posts, and not for updates, you could put a similar statement there instead of in writeNewPost()
.
Answered By - Bob Snyder
Answer Checked By - Robin (JavaFixing Admin)