Skip to content Skip to sidebar Skip to footer

How To Populate A Spinner With The Result Of A Firestore Query?

I am creating a spinner which will show the subject name. The subject names are stored in my Firestore database as follows: subjects (collection) | |--- SUB01 (document) | | |

Solution 1:

To solve this, please use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference subjectsRef = rootRef.collection("subjects");
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> subjects = newArrayList<>();
ArrayAdapter<String> adapter = newArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, subjects);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
subjectsRefRef.get().addOnCompleteListener(newOnCompleteListener<QuerySnapshot>() {
    @OverridepublicvoidonComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshotdocument : task.getResult()) {
                String subject = document.getString("name");
                subjects.add(subject);
            }
            adapter.notifyDataSetChanged();
        }
    }
});

The result will be a spinner that will contain 2 items:

Android
Java

Post a Comment for "How To Populate A Spinner With The Result Of A Firestore Query?"