简体   繁体   中英

Is there a way to store data values from firestore into an array?

I am trying to get data in a two specific field in each document where one field is a integer and the other is a string. I want each field to be stored in an array separately.

 db.collection("Activity")
                .whereEqualTo("plan_id", plan_id)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            List<Long> progressList = new ArrayList<>();
                            List<String> titleList = new ArrayList<>();
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                Log.d(TAG, document.getId() + " => " + document.get("progress"));

                            }
                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
                });

I've tried

int[] prog = (int[]) document.get("progress");
String[] title = (String[]) document.get("title");

but no luck...

I am not familiar with Firestore, but it seems that the QueryDocumentSnapshot is similar to Map<String, Object> . Following code snippet shows how to store those values into List as declared in your code - progressList and titleList, respectively.

List<int> progressList = new ArrayList<>();
List<String> titleList = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
    progressList.add(Integer.valueOf(document.get("progress").toString()));
    titleList.add(document.get("title").toString());
}

And if you still want to use Array to store values, you can use API ArrayList.toArray() as follows:

int[] prog = new int[progressList.size()];
prog = progressList.toArray(prog);

String[] title = new String[titleList.size()];
title = titleList.toArray(title);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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