Reputation: 61
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.
Upvotes: 4
Views: 4808
Reputation: 138969
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
Upvotes: 10