我尝试在Firebase中添加时间戳,但我很遗憾地失败了。我已经尝试过stackoverflow的许多建议,但没有一个工作。请帮我详细说明如何在每个帖子下添加时间戳字段。
我想知道我的代码有什么问题。
final DatabaseReference newPost = mDatabase.push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long timestamp = (Long) dataSnapshot.getValue();
System.out.println(timestamp);
newPost.child("title").setValue(title_val);
newPost.child("desc").setValue(desc_val);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("username").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabaseUser.setValue(ServerValue.TIMESTAMP);
mProgress.dismiss();
Firebase数据库结构:
{
"Blog":{
"-Ke1osQRFVs0fuqx9n18":{
"desc":"again again",
"uid":"FBwMzHJGP4U10LnLOwluy4BVyJ52",
"username":"OziBoo"
}
},
"Users":{
"vi6Qd1AafidNGGV4roBhdLPZYGN2":{
"image":"firebasestorage.googleapis.com/v0/b/agrodesk-b30ff.appspot.com/...",
"name":"Ozi"
}
}
}
答案 0 :(得分:0)
您的代码中存在大量错误和误用。请先理解这一点:
ref.addValueEventListener(...)
用于收听ref
ref.setValue(yourValue)
用于设置ref
object setValue(...).addOnCompleteListener(...)
如果我理解正确,你编写的所有示例代码都是为了将值写入数据库,对吧?但是,您并非故意使用addValueEventListener()
代替。
因此,将值写入"Blog"
内的新子代的代码应如下所示:
// Here I use HashMap to make it more simple
// You can (and better to) use your custom object as value container
HashMap<String, Object> value = new HashMap<>();
value.put("title", "your-title");
value.put("desc", "your-desc");
value.put("timestamp", ServerValue.TIMESTAMP);
// ... etc
// the following code will create a reference object pointing at "Blog"
DatabaseReference ref = FirebaseDatabase.getInstance().getRreference("Blog");
// the following code will make a new child inside data referenced by ref (in this case, "Blog")
DatabaseReference newBlog = ref.push();
// the following code is the code that actually update the data of referenced point
newBlog.setValue(value)
// addOnCompleteListener is optional
.addOnCompleteListener(new ... {
// code placed here will be executed when your data is updated
...
});
希望这有帮助。
注意:
在那里,我只是向您展示您希望为此案例和本案例实现的目标。请阅读有关Firebase数据库的更多文档,指南和教程。这可能需要很长时间,但一旦你明白了,它实际上很简单。