在我的Android应用中使用ServerValue.TIMESTAMP [英] Using ServerValue.TIMESTAMP in my Android App
问题描述
我已经阅读了很多与stackoverflow相关的问题
I have read lots of stackoverflow questions related to
ServerValue.TIMESTAMP
但是我不知道如何在我的应用程序中使用它.
but I can't figure out how to use it in my app.
我需要获取创建帖子的时间戳. 应该将timeStamp与帖子的uid,author等添加到同一位置.
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.
编写帖子 firebase数据库的代码段:
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);
}
我的 Post.java 文件
@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]
}
我应该如何使用
ServerValue.TIMESTAMP
在我的代码中获取创建帖子的时间.
in my code to get the time of creation of post.
推荐答案
ServerValue.TIMESTAMP 只是一个占位符值.当Firebase服务器处理更新请求并找到ServerValue.TIMESTAMP
作为值时,它将替换为当前服务器时钟.
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.
在您的writeNewPost()
方法中,您可以添加一行以设置创建时间:
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);
如果仅将Post.toMap()
用于创建帖子,而不用于更新,则可以在其中放置类似的语句,而不要放在writeNewPost()
中.
If you use Post.toMap()
only to create posts, and not for updates, you could put a similar statement there instead of in writeNewPost()
.
这篇关于在我的Android应用中使用ServerValue.TIMESTAMP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!