简体   繁体   中英

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) {

                }
            });

}

数据库

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);


}

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