How to populate a spinner with the result of a Firestore query?

Issue

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)
|    |
|    |--- name : "Android"
|
|--- SUB02
|    |
|    |--- name : "Java"

I could fetch the result to an RecyclerView but unable to help myself to do so for spinner.

Solution

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 = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, subjects);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
subjectsRefRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : 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

Answered By – Alex Mamo

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published