如何从Firebase检索数据并在TextView中显示它们?

时间:2019-02-07 16:47:56

标签: java android firebase firebase-realtime-database

My firebase database structure is look like this

mAuth = FirebaseAuth.getInstance();

mUser = mAuth.getCurrentUser();

userID = mUser.getUid();

mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");

mDatabaseReference.addValueEventListener(new ValueEventListener() {

   @Override

   public void onDataChange(DataSnapshot dataSnapshot) {
            showData(dataSnapshot);
        }

   @Override

   public void onCancelled(DatabaseError databaseError) {

        }
});

private void showData(DataSnapshot dataSnapshot) {


   for (DataSnapshot ds : dataSnapshot.getChildren()) {

       UserInformation uInfo = new UserInformation();



uInfo.setFullName(ds.child(userID).getValue(UserInformation.class).getFullName()); // Set Full Name

             uInfo.setUsername(ds.child(userID).getValue(UserInformation.class).getUsername()); // Set Username

      uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail());

        fullNameProfile.setText(uInfo.getFullName());
        usernameProfile.setText(uInfo.getUsername());
        emailProfile.setText(uInfo.getEmail());
    }
}

我正在使用此代码,但是它没有从数据库中检索任何数据,有时getUid()会产生NullPointerException。谁能帮助我解决这个问题?

1 个答案:

答案 0 :(得分:0)

要简单地从数据库中获取用户数据,请使用以下代码行:

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 email = dataSnapshot.child("Email").getValue(String.class);
        String fullName = dataSnapshot.child("FullName").getValue(String.class);
        String password = dataSnapshot.child("Password").getValue(String.class);
        String userName = dataSnapshot.child("Username").getValue(String.class);
        Log.d(TAG, userName);
    }

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

或更简单的使用UserInformation类:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        UserInformation uInfo = dataSnapshot.getValue(UserInformation.class);
        Log.d(TAG, uInfo.getUsername());
    }

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