简体   繁体   中英

I'm reading some data from Firebase database but it returned object is null

Here is my firebase structure Fire Base Structure

I am trying to fetch phone value from firebase but it is giving null.

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference

 //getting user id value
    SharedPreferences settings = getSharedPreferences("myapp", MODE_PRIVATE);


    // Reading from SharedPreferences

    String uid = settings.getString("uid", "");
    userId = uid;
    mFirebaseDatabase.child("users").child(userId).child("phone").addValueEventListener(new ValueEventListener() {
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            phone = dataSnapshot.getValue(String.class);
            Log.d(TAG, "Value is: " +phone);

        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }

    });

textview.setText(phone);

Please give some suggestion i don't know why it is returning null Thanks

Your error is here :

string uid = settings.getString("uid","")

You're pushing the values using the random key and your code is unable to locate to that key rhat is why its giving null

Solution : In the code where you're pushing the values to the database instead of push just use

FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(your value model class variable) 

Now in your fetching code just replace uid with

FirebaseAuth.getInstance().getCurrentUser().getUid()

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