简体   繁体   English

如何从 Firestore 的特定文档中的 map 检索数据

[英]How to retrieve data from a map inside a particular document of firestore

The document is user Id and I want to retrieve "Address1" of a particular user from the map "Address".该文档是用户 ID,我想从 map“地址”中检索特定用户的“地址 1”。 在此处输入图像描述

 private FirebaseFirestore mfirestore;
    DocumentReference docRef;

    private FirebaseAuth mAuth;
    private FirebaseUser user;



 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_address);
   mAuth = FirebaseAuth.getInstance();
        user = mAuth.getCurrentUser();
        uid = user.getUid();
        docRef = mfirestore.collection("user").document(uid);


    }

   @Override
    protected void onStart() {
        super.onStart();
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        if (document.getData().get("Address")!=null){
                            String Address=document.getData().get("Address").toString();
                           
                        }
                       
                    }





                } else {
                    Toast.makeText(UserAddress.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });

I have retrieve the whole "Address" but not able to find a way to get address1 of the user seperately.我已经检索了整个“地址”,但无法找到单独获取用户地址 1 的方法。

Map type document fields show up in Java as type Map<String, Object> . Map 类型的文档字段在 Java 中显示为Map<String, Object>类型。 If you are accessing a map, you can simply cast it:如果您正在访问 map,您可以简单地转换它:

Map<String, Object> address = (Map<String, Object>) document.getData().get("Address");

Now you can use that map to access its individual fields:现在您可以使用 map 访问其各个字段:

String address1 = (String) address.get("Address1");

Ideally you should also check the type a nullity of each value before you cast it, or you might throw an exception.理想情况下,您还应该在强制转换之前检查每个值的类型是否为空,否则您可能会抛出异常。

This is how you would do it in Kotlin.这就是你在 Kotlin 中的做法。

db.collection("app-version")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {

                val versionNum = document.get("versionNumber").toString()
                binding.txtAppVersion.text = versionNum


            }
        }
        .addOnFailureListener { exception ->

            Toast.makeText(
                this, "No such document", Toast.LENGTH_SHORT
            )
                .show()
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM