我在文档中存储了一个字符串列表。我已经给了它一个名称(“名称”),现在我试图将它放在客户端,但不知道如何准确地做到这一点。我可以看到,如果我的字段是数字类型,我可以使用
getLong("Fieldname")
但我无法弄清楚如何获取字符串类型列表。
到目前为止我的代码
FirebaseFirestore getlistofbrands=FirebaseFirestore.getInstance();
getlistofbrands.collection(FireStoreConstants.COL_BRANDNAMESONLY).document("Brands").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<String> listofbrandsfromfirestore=queryDocumentSnapshots.getDocuments().toArray(String.class);
也尝试过这个
List<String> listofbrandsfromfirestore=queryDocumentSnapshots.toObjects(String.class);
我如何上传数据
Map < String, Object > docData = new HashMap < > ();
List < String > deviceNameList = new ArrayList < String > ();
deviceNameList.add("brand1");
deviceNameList.add("brand2");
deviceNameList.add("brand3");
deviceNameList.add("brand4");
docData.put("name", deviceNameList);
firebaseFirestore.collection("FireStoreConstants.COL_BRANDNAMESONLY")
.document("Brands").set(docData).addOnSuccessListener(new
OnSuccessListener < Void > () {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Repository:onSuccess:");
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(TAG, "Repository:error" + e.toString());
}
});
由于您将品牌名称存储在单个文档中,因此我怀疑 QuerySnapshot 是否是要返回的正确类。据我所知,您需要使用
getData()
来获取 Firestore 用于您的 Map<String, Object>
的 List
:
getlistofbrands
.collection(FireStoreConstants.COL_BRANDNAMESONLY)
.document("Brands")
.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());
Map<String, String> brandsMap = (Map<String, String>)document.getData().getData("AllBrands");
List<String> brands = new LinkedList<String>();
for (String key: brandsMap.keySet()) {
brands.add(brandsMap.get(key));
}
// TODO: use the brands list
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
您可能还想尝试:
List<String> brands = brandsMap.value();
我使用了@Frank van 提供的代码,并使用此函数将我的对象转换为字符串列表
@SuppressWarnings("unchecked")
public static <T extends List<?>> T cast(Object obj) {
return (T) obj;
}
Object brandsobj = queryDocumentSnapshots.getData().get("AllBrands");
List<String> allbrands = cast(brandsobj);