java - 如何在不使用事件侦听器的情况下从 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();
}
}
}
});
}
请帮忙!看到这个问题的另一种方法是:我需要一种将字符串“数据”发送到另一个函数的方法。
解决方案
正如您在文档中看到的那样,您必须使用返回的任务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 - 您必须阅读整个文档,然后从中找到您想要的字段。
推荐阅读
- android - 如何修复 Android Studio 中未找到的 Android 插件
- electron - 在 Electron 中使用 Elm 0.19 时无法读取未定义的属性“Elm”
- java - 如何使用 TomEE 保护 jax-rs Web 服务?
- c# - Async Task.Run 在自托管的 Web 服务中运行 - 只要它有效,它就是“错误使用”吗?
- python - 无法加入字符串类型的熊猫数据框
- php - Laravel Passport 不生成令牌
- javascript - 网格视图未正确显示
- c++ - 如何通过引用将 c++ 字符串分配给另一个字符串
- three.js - 如何使用three.js旋转平面?
- python - 如何创建一个函数来查找可被 7 整除但不能被 5 整除的数字