Reputation: 1
I am trying to retrieve value(phone number) for a child from my firebase realtime database. However it gives me the following error:
Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
The structure of my database looks like this:
contactsfirebase-16ade
users
-LiKtfTuDQm7LmY49t69
email: "[email protected]"
name: "dev"
phone: "2327272"
Code
DatabaseReference databaseReference;
databaseReference.child("users").child("userID").child("phone").addListenerForSingleValueEvent(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
String phone = dataSnapshot.getValue().toString();
Phone.setText(phone);
Phone.getDisplay();
}
}
Read child value from firebase
I want the value "2327272" to be shown in the textview Phone on my app. However when I click the button it gives the error as shared above and the app crashes.
Upvotes: 0
Views: 1411
Reputation: 1957
You can try this method :
@Override
protected void onStart() {
super.onStart();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
//if you retrive the Uid inside of oncreate method you can call it else you have to retrive the Uid
DatabaseReference veera = rootRef.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid();
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("phone").exits()){
String phone = dataSnapshot.getValue().toString();
Phone.setText(phone);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
veera.addValueEventListener(eventListener);
}
If you are doing in under a button click just move it to a public method and call the method inside of onclicklistener.
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//here
}
}
Upvotes: 0
Reputation: 13129
Your DatabaseReference databaseReference;
is not initialized
Do this
DatabaseReference databaseReference;
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("users").child("userID").child("phone").addListenerForSingleValueEvent...
Upvotes: 1