我的数据库:
我想从firebase数据库中检索用户ID。我怎么能这样做?
我的代码是:
///////////// Recycler Firebase /////////////
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class,
R.layout.post_row,
PostViewHolder.class,
dbpostShow
) {
@Override
protected void populateViewHolder(final PostViewHolder viewHolder, Post model, int position) {
String listPostKey = getRef(position).getKey();
viewHolder.setTextPost(model.getText_post());
viewHolder.setHospitalName(model.getHospital_name());
viewHolder.setFullNameUserPoster(model.getPoster_name());
viewHolder.setAgeUserPoster(model.getPoster_age());
String lastSeenAgo = GetTimeAgo.getTimeAgo(model.getTime_post_ago(), getContext());
viewHolder.setTimePostAgo(lastSeenAgo);
viewHolder.setTypeBloodneedPoster(model.getPoster_type_blood());
Toast.makeText(getActivity(), model.getPoster_type_blood(), Toast.LENGTH_SHORT).show();
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
答案 0 :(得分:2)
如果您已在userId
类中创建变量Post
并使用getter获取值。
否则,您可以使用addListenerForSingleValueEvent
获取值:
以下是如何使用它的示例。
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Post, PostViewHolder>(
Post.class,
R.layout.post_row,
PostViewHolder.class,
dbpostShow
) {
@Override
protected void populateViewHolder(final PostViewHolder viewHolder, Post model, int position) {
String listPostKey = getRef(position).getKey();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Post").child("country").child("city").child(listPostKey).child("userId");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userID = String.valueOf(dataSnapshot.getValue());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
答案 1 :(得分:0)
在下面的代码中添加了您的用户ID时,您无法跟踪价值,并确保您的父级位置正确
yourRef.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
})