简体   繁体   中英

Read a particular child value from firebase database

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: "devsingh0@gmail.com"
      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.

Your DatabaseReference databaseReference; is not initialized

Do this

DatabaseReference databaseReference; 
databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("users").child("userID").child("phone").addListenerForSingleValueEvent...

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
      }
      }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM