如何在firebase实时数据库中获取push()方法添加的指定数据子项?
嗨,我在firebase实时数据库中有以下数据子项: -
我正在使用 child.push()
方法来保存数据,以便每当注册Posts子项时它都会生成一个随机密钥 . 每个帖子还有一个发布它的用户的用户ID,这也是一种主键 .
以下是我写新帖子的代码: -
private void writeNewPost(String userId, String tittle, String address, String locationLat, String locationLong, String date, String extrass, String postId) {
Alerts alerts = new Alerts(userId, tittle, address, date, locationLat, locationLong, extrass, postId);
String key = mDatabaseUsers.push().getKey();
// String key = mDatabase.child("posts").push().getKey();
mDatabaseUsers.child("Posts").child(key).setValue(alerts, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError error, DatabaseReference ref) {
Log.d("ssd", "onComplete: " + error);
}
});
}
现在我想要检索一个特定的帖子,但我无法理解,例如我有 RecyclerView
我在哪里显示所有帖子 . 当用户点击特定帖子时应该检索帖子以及来自firebase的数据,但我无法理解 . 我这样使用了 addValueEventListener
: -
mDatabase.child("Posts").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String key = mDatabase.push().getKey();
// String name = (String)
dataSnapshot.child("name").getValue();
// String mobile = (String) dataSnapshot.child("phoneNumber").getValue();
// String additionalIn = (String) dataSnapshot.child("extras").getValue();
// String address = (String) dataSnapshot.child("address").getValue();
// String profile_pic = (String) dataSnapshot.child("address").getValue();
String post_uid = (String) dataSnapshot.child("userid").getValue();
String post_tittle = (String) dataSnapshot.child("tittle").getValue();
// if (mAuth.getCurrentUser().getUid().equals(post_uid)){
//
// deleteBtn.setVisibility(View.VISIBLE);
// }
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d("OMG", "onCancelled: " + databaseError);
}
});
}
}
但我无法理解如何在 onClick()
或任何其他类似的回调方法中检索特定的子项 .
1 回答
要根据其ID检索用户信息:
用户点击帖子后,您可以通过
orderByKey().equalTo(userid)
用用户's id and then you can retrieve, the user'的信息检索该帖子的数据