Accessing data stored as Object in Firestore database

前端 未结 1 1006
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 16:52

Recently I started testing Firebase new document db Firestore for learning purpose, I am stuck right now to access the values store inside the document as object.

1条回答
  •  青春惊慌失措
    2021-02-15 17:13

    The privacy field within your document can be considered a Map, so you could cast the value of this field into such a variable:

    HashMap privacy = (HashMap) task.getResult().getData().get("privacy");
    

    Now the main problem with this is that you'll likely see an "unchecked cast" compiler warning because casting a Map like this is not ideal as you can't guarantee that the database structure will always contain String : Boolean values in this field.

    In this case, I would suggest using custom objects to store & retrieve objects in your database, which will automatically deal with marshalling and casting for you:

    DocumentReference docRef = FirebaseFirestore.getInstance().collection("Users").document("PQ8QUHno6QdPwM89DsVTItrHGWJ3");
    docRef.get().addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document != null) {
                    User user = task.getResult().toObject(User.class);
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException());
            }
        }
    });
    

    Where your User class is something like:

    public class User {
        private String username;
        private HashMap privacy;
    
        public User() {}
    
        public User(String username, HashMap privacy) {
            this.username = username;
            this.privacy = privacy;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public HashMap getPrivacy() {
            return username;
        }
    
        public void setPrivacy(HashMap privacy) {
            this.privacy = privacy;
        }
    }
    

    In this example, the User user = task.getResult().toObject(User.class) call will marshall the entire document into an instance of your User object, and you can then access the privacy map with:

    HashMap userPrivacy = user.getPrivacy();
    

    Each field in the document will be matched to a field with the same name within your custom object, so you could also add the settings or photo_url fields in the same fashion. You just need to remember:

    Each custom class must have a public constructor that takes no arguments. In addition, the class must include a public getter for each property.

    0 讨论(0)
提交回复
热议问题