I'm not able to retrieve any of the values from my datasnapshot. I've tried several methods and techniques, but it's given a null value.
The image of my database is above. Please see my code below,trying to log a value, everything seems right but not working.
email = view.findViewById(R.id.email);
editTextfragmentF = view.findViewById(R.id.editText_firstname);
editTextfragmentL = view.findViewById(R.id.editText_lastname);
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String UserID = mAuth.getCurrentUser().getUid();
FirebaseDatabase database = FirebaseDatabase.getInstance();
database.getReference().child("Users").child(UserID).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
if (mAuth.getCurrentUser() != null) {
email.setText(mAuth.getCurrentUser().getEmail());
//Gets current users first name
String FN = String.valueOf(dataSnapshot.child("firstName").getValue());
Log.i("First Name", FN);
/*String LN = dataSnapshot.child("lastName").getValue().toString();
Log.i("Last Name", LN);*/
/*editTextfragmentF.setText(FN);
editTextfragmentF.requestFocus();*/
/*editTextfragmentL.setText(LN);
editTextfragmentL.requestFocus();*/
}
}
The Result:
you need to change
database.getReference().child("Users").child(UserID).addChildEventListener
with
database.getReference().child("Users").child(UserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
email.setText(dataSnapshot.child("email").getValue(String.class));
String FN = dataSnapshot.child("firstName").getValue(String.class);
Log.i("First Name", FN);
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Make sure you have granted internet access in your AndroidManifest.xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
getValue() takes in type of object to be returned. In your case your are getting a string value so just pass String.class into the method then save it into a String variable.
String firstname=dataSnapshot.getValue(String.class);
Log.i("First Name", firstname);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.