从Firebase数据库中检索特定用户的数据

时间:2019-09-11 02:41:52

标签: java android firebase-realtime-database

我正在尝试从data中检索Firebase Realtime Database。工作正常我的问题是如何从userDatabase设置文本。结果将为null,我认为使用database时不会读取userID

    FirebaseUser user = firebaseAuth.getCurrentUser();

    String userid = user.getUid();

    txvEmail = (TextView) findViewById(R.id.txvEmail);
    txvEmail.setText("Welcome "+user.getEmail());

    txvName = (TextView) findViewById(R.id.txvName);
    txvAdd =(TextView) findViewById(R.id.txvAdd);

    userDatabase = new UserDatabase();

    reff = FirebaseDatabase.getInstance().getReference("Member").child(userid);
    reff.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            txvName.setText(" "+userDatabase.getFirstName()+" "+userDatabase.getLastName());

        }

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

        }
    });

1 个答案:

答案 0 :(得分:4)

我认为您必须将模型类定义为快照值

txvEmail = (TextView) findViewById(R.id.txvEmail);
txvEmail.setText("Welcome "+user.getEmail());

txvName = (TextView) findViewById(R.id.txvName);
txvAdd =(TextView) findViewById(R.id.txvAdd);

userDatabase = new UserDatabase();

reff = FirebaseDatabase.getInstance().getReference("Member").child(userid);
reff.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        //new code
        for(DataSnapshot snap: dataSnapshot.getChildren()){
            //you must define your class model to the value of snapshots
            userDatabase user = snap.getValue(userDatabase.Class);
             txvName.setText(" "+user.getFirstName()+" "+user.getLastName());
       }


    }

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

    }
});