且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Firebase检索/读取返回空值 - Android

更新时间:2023-01-18 19:00:40

数据被返回现在,实现最后会有太多的嵌套,所以现在帖子在一个单独的节点。更改后的代码:

 最终Firebase userRef = rootRef.child(users /+ rootRef.getAuth()。getUid() ); 

到:

  final Firebase userRef = rootRef.child(posts); 


Using Firebase docs for retrieving data with:

ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        System.out.println(snapshot.getValue());
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
}); 

Running the above produced:

{users={facebook:###############={posts={-KE8qg1VyPAwYj0uJDcn={status=update1}}, provider=facebook, displayName=Some Name}}}

Created class to represent users:

@JsonIgnoreProperties(ignoreUnknown=true) //to ignore mapping issues
public class Users {

String status;
String displayName;
String provider;

public Users() {
        // empty default constructor
}

public String getStatus() {
    return status;
}

public String getName(){
    return displayName;
}

public String getProvider(){
    return provider;
}
}

Using the following to attempt to retrieve values:

ref.addChildEventListener(new ChildEventListener() {
        // Retrieve new posts as they are added to the database
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            Users newUser = snapshot.getValue(Users.class);
            System.out.println("Status: " + newUser.getStatus());
            System.out.println("Display Name: " + newUser.getName());
            System.out.println("Provider: " + newUser.getProvider());
        }

Everything returns a null? Read over & tried several examples of using for loops to iterate over the database but those failed as well so I decided to come back to the first version. Not certain which way is best for this situation?

Data is returned now. Realized in the end there would be too much nesting so now posts are in a separate node. Changed code from:

final Firebase userRef = rootRef.child("users/" + rootRef.getAuth().getUid());

to:

final Firebase userRef = rootRef.child("posts");