Skip to content
Advertisement

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

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement