Skip to content
Advertisement

How to retrieve arrays from FirebaseFirestore using Collections?

This is my Firestore database

db.collection("PublicFormDetails")
                .whereEqualTo("Topic Name",message)
                .get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if(task.isSuccessful())
                {
                    for (QueryDocumentSnapshot snapshot : Objects.requireNonNull(task.getResult())) {
                        String value1 = snapshot.getString("QuestionName");
                        Toast.makeText(PublicVote.this, value1, Toast.LENGTH_SHORT).show();
                        q_tv1.setText("Question: "+value1);
                    }
                }
                }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(PublicVote.this,e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

Now here I want to retrieve Description and No. of Options which is saved in the form of an array, my code above prints other details of the data as well, with respect to the topic name selected hence I’ve used whereEqualTo(“Topic Name”, message)as my query(where the message is the topic I select). How to retrieve Description and No. of Options now in this. I can’t use DocumentReference because then I won’t be able to use whereEqualsTo. Please help!!!

Advertisement

Answer

To get the content of those two araays, please add the following two lines of code inside the for loop:

List<String> description = (List<String>) snapshot.get("Description");
List<String> noOfOptions = (List<String>) snapshot.get("Np. of Options");

Right after this line:

q_tv1.setText("Question: "+value1);

If you need each element within those arrays, create a for loop for each list and get the corresponding data.

The result in the logcat will be:

Hey
What's up?

For the first array, and:

123
456

For the second array.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement