从Firebase数据库读取特定数据

时间:2019-11-07 17:21:36

标签: java android firebase firebase-realtime-database

我正在尝试从当前用户加载特定孩子的孩子,但是它正在显示所有用户的信息。

image of Firebase database screenshot of emulator

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View v = inflater.inflate(R.layout.activity_user_profile, container, false);

        btEdit = v.findViewById(R.id.button_edit);
        mChildValueTextView = v.findViewById(R.id.childValueTextView);
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        final DatabaseReference mRef = database.getReference("Users");

        mRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String childValue = String.valueOf(dataSnapshot.getValue());
                mChildValueTextView.setText(childValue);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 
    {

1 个答案:

答案 0 :(得分:0)

使用以下代码行:

String childValue = String.valueOf(dataSnapshot.getValue());

这意味着您将在Users节点内吸引所有用户。如果要获得单个用户(即已认证的用户),则应在树中更深入一些。我假设fp60 ... Xez1是来自身份验证过程的用户的ID,要获取其数据,请使用以下代码行:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String age = dataSnapshot.child("age").getValue(String.class);
        String name = dataSnapshot.child("name").getValue(String.class);
        String sex = dataSnapshot.child("sex").getValue(String.class);
        Log.d("TAG", name + ", " + sex + ", " + age);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

假设经过身份验证的用户将上面的示例fp60 ... Xez1作为uid,则logcat中的输出将为:

carlostest2, m, 28