Gaurav Bhagat
Gaurav Bhagat

Reputation: 97

Unable to fetch data from Firebase (Android)

I am trying to fetch the data from the google firebase but every time i tried to fetch the data. "Else" case is running everytime. Tried to change if(dataSnapshot.exists()) but getting the same error. Please help to resolve it.

public void retrieveProfileInfo() {
    currentUserID = mAuth.getUid();
    key = rootRef.child("profiles").push().getKey();
    rootRef.child("users-profiles").child(currentUserID).child(key)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    try {
                        if ((dataSnapshot.child("name").getValue()) != null){
                            String retrieveName = dataSnapshot.child("name").getValue().toString();
                            String retrieveStatus = dataSnapshot.child("about").getValue().toString();
                            nameBox.setText(retrieveName);
                            aboutBox.setText(retrieveStatus);
                        } else {
                            Toast.makeText(UserProfileActivity.this, currentUserID+"else - retrieveProfileInfo()",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }catch (Exception e){
                        Log.i("retrieveProfileInfo : ", "error is : " + e);
                        Toast.makeText(UserProfileActivity.this, e+" : Error",
                                Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

}

Database

Upvotes: 0

Views: 55

Answers (1)

Hasan Bou Taam
Hasan Bou Taam

Reputation: 4035

You cant push a random key and read from it, you need to loop through children under users-profile/userID:

public void retrieveProfileInfo() {

//current user ID
currentUserID = mAuth.getUid();

ValueEventListener listener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

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

       //get the values
       String name = ds.child("name").getValue(String.class);
       String about = ds.child("about").getValue(String.class);
       String uid = ds.child("uid").getValue(String.class);


      }       
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        // log error
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

    }
};
rootRef.child("users-profiles").child(currentUserID).addValueEventListener(listener);


}

Upvotes: 1

Related Questions