我一段时间以来一直在尝试在 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"
}
}
}
最佳答案
您的代码中有很多错误和误用。请先理解这一点:
ref.addValueEventListener(...)
用于监听ref
引用的数据中所做的每个更改ref.setValue(yourValue)
用于设置ref
对象引用的数据的值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
...
});
希望这有帮助。
Note:
There I just show you what you want to achieve for this case and this case only. Please read more documentation, guide, and tutorial about Firebase Database. It might take long, but once you understand it, it's actually quite simple.
关于android - 将时间戳发布到 Android Firebase 数据库不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42500076/