Convert Firebase field array to list

匿名 (未验证) 提交于 2019-12-03 01:40:02

问题:

I'm trying to convert a field which has an array in Firebase Cloud Firestore. The field is stored in a document and contains 10 values in the field.

I can get the data using the following code however I would like to know if its possible to convert this data into a List?

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

I have tried the following however, it doesn't compile saying:

"Cannot resolve constructor 'ArrayList(java.util.Map<java.lang.String,java.lang.Object>)"

This is my code:

List<String> allowedData = new ArrayList<String>(task.getResult().getData());

The database structure is as follows:

回答1:

Create a forEach loop to iterate through each field, cast it to String and add it to the ArrayList:

docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {             @Override             public void onComplete(@NonNull Task<DocumentSnapshot> task) {                 if (task.isSuccessful()) {                     DocumentSnapshot document = task.getResult();                     if (document != null) {                         Log.d(TAG, "DocumentSnapshot data: " + task.getResult().getData());                         for(Object item : task.getResult().getData().values())                             allowedData.add(item.toString());                     } else {                         Log.d(TAG, "No such document");                     }                 } else {                     Log.d(TAG, "get failed with ", task.getException());                 }             }         });


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!