首页 > 解决方案 > 如何在不使用事件侦听器的情况下从 Firestore 文档中获取单个字段?

问题描述

这段代码正在工作,但不是我想要的方式,我需要一种方法来将单个值(“秘密密钥”)提取到字符串“用户”中,而不使用事件侦听器,因为我需要一种方法来将此字符串变量发送到另一个函数,所以它可以被加密。我希望注释行中的代码能够工作,或者类似的东西。

 public void getData() {

        String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
        DocumentReference user = fStore.collection("Users").document(currentUser);
        //I WANT THIS TO WORK/////////////////////////////////////////////////////////////////////
        String users = fStore.collection("Users").document(currentUser).get("secretKey").toString();
        Log.d("LOGGER", users.toString());
        //////////////////////////////////////////////////////////////////////////////////////////
        user.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {
                if (value.exists()){

                    String secretKey = value.getString("secretKey");
                    String groupID = value.getString("groupID");
                    String data = secretKey +":::"+ groupID;

                    StringBuilder textToSend = new StringBuilder();
                    textToSend.append(data);
                    MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
                    try {
                        BitMatrix bitMatrix = multiFormatWriter.encode(textToSend.toString(), BarcodeFormat.QR_CODE, 600, 600);
                        BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
                        Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);

                        imageView.setImageBitmap(bitmap);
                        imageView.setVisibility(View.VISIBLE);

                    } catch (WriterException e) {
                        e.printStackTrace();
                    }


                }

            }
        });
    }

请帮忙!看到这个问题的另一种方法是:我需要一种将字符串“数据”发送到另一个函数的方法。

标签: javaandroidfirebasegoogle-cloud-firestore

解决方案


正如您在文档中看到的那样,您必须使用返回的任务get()来异步接收文档的内容。你不能随便打电话。这是该链接中显示的内容:toString()

DocumentReference docRef = db.collection("cities").document("SF");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Log.d(TAG, "DocumentSnapshot data: " + document.getData());
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException());
        }
    }
});

它并没有比这更短。

您可以使用 DocumentSnapshot 对象从您需要的文档中获取单个字段。没有用于仅获取单个字段的 API - 您必须阅读整个文档,然后从中找到您想要的字段。


推荐阅读