Android:从子集合获取字段值

huangapple go评论81阅读模式
英文:

Android: Get field values from sub-collection

问题

以下是您请求的翻译内容:


从子集合获取数据的方法有吗?下面是我的数据库结构,对于每个用户,在“userinfo”子集合中只会创建一个文档,用于存储用户名和电子邮件。

我正在尝试从Firestore获取“username”和“email”值,然后将这些值设置为字符串,如下所示:

String username = ?
String email = ?

"main"(根集合)
            |
            |=>userid1(自动生成)
                         |                  
                         |=>"userinfo"(子集合)=>documentID(自动生成)=>username: mary
                         |                                              =>email: mary@gmail.com
                         |                                             
                         |                            
                         |=>"emotions"(子集合)=>documentID(自动生成)=>happy: true
                                                                        =>sad: false
                                                                        =>depressed: false

我阅读了一些其他问题的答案,说可以使用以下方式检索字段值:

String value = documentSnapshot.getString("field");

但我仍然不知道该如何做?我写了一些代码,但不知道如何获取值。

FirebaseAuth mAuth = FirebaseAuth.getInstance();
String userId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();

FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference userRef = db.collection("main").document(userId).collection("userinfo");

userRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
        //获取值
        String value = queryDocumentSnapshots.getDocuments("username"); // 如何获取??
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
});

还有一个UserInfo对象类:

import java.io.Serializable;

public class UserInfo implements Serializable {

    private String email, username;

    public UserInfo() {}

    public UserInfo(String email, String username) {
        this.email = email;
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

请帮助,非常感谢。

英文:

Is there a way to get data from sub-collection? Below is the structure of my database, for each user, only one document will be created in the "userinfo" subcollection to store just the username and email.

I am trying to get the "username" and "email" values from Firestore then set the values to strings like:

String username = ?
String email = ?

&quot;main&quot;(root_collection)
            |
            |=&gt;userid1(auto-generated)
                         |                  
                         |=&gt;&quot;userinfo&quot;(sub-collection)=&gt;documentID(auto)=&gt;username: mary
                         |                                              =&gt;email:mary@gmail.com
                         |                                             
                         |                            
                         |=&gt;&quot;emotions&quot;(sub-collection)=&gt;documentID(auto)=&gt;happy: true
                                                                        =&gt;sad:false
                                                                        =&gt;depressed:false
                

I read some other answers from other questions saying that the field value could be retrieved using

String value = documentSnapshot.getString(&quot;field&quot;);

but I still don't know how to do it? I wrote a little something and I don't know how to get the value.

 FirebaseAuth mAuth = FirebaseAuth.getInstance();
        String userId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        CollectionReference userRef = db.collection(&quot;main&quot;).document(userId).collection(&quot;userinfo&quot;);

        userRef.get().addOnSuccessListener(new OnSuccessListener&lt;QuerySnapshot&gt;() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                //get the value
                String value = queryDocumentSnapshots.getDocuments(&quot;username&quot;); // how ??
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

also have an object class UserInfo

import java.io.Serializable;

public class UserInfo implements Serializable {

    private String email, username;

    public UserInfo() {}

    public UserInfo(String email, String username) {
        this.email = email;
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Please help, thanks so much.

答案1

得分: 2

是的,有方法可以从子集合获取数据。要获取该数据,您必须像以下代码中的循环一样遍历结果:

userRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                String value = document.getString("username");
                Log.d("TAG", value);
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

在 logcat 中的结果将会是:

mary
英文:

> Is there a way to get data from sub-collection?

Yes, there is. To get that data, you have to loop through the result as in the following lines of code:

userRef.get().addOnCompleteListener(new OnCompleteListener&lt;QuerySnapshot&gt;() {
    @Override
    public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                String value = document.getString(&quot;username&quot;);
                Log.d(&quot;TAG&quot;, value);
            }
        } else {
            Log.d(TAG, &quot;Error getting documents: &quot;, task.getException());
        }
    }
});

The result in the logcat will be:

mary

huangapple
  • 本文由 发表于 2020年4月9日 18:29:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/61119106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定