Retrieve data of a specific user from a Firebase database

Afiq Ilman :

I am trying to retrieve data from Firebase Realtime Database. It's working. My question is how to set text from userDatabase. The result will be null and I think it does not read the database while using 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) {

        }
    });
Cyrille Con Morales :

I think you must define your model class to values of snapshots

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) {

    }
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307395&siteId=1
Recommended