Reputation: 401
I want to populate a spinner with a list of strings from a table in my firebase database.
I want the spinner to contain the items category name , so Test, Nature etc.
My xaml looks like this:
<Spinner
android:spinnerMode="dialog"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/spinnerCategory"
android:layout_margin="7dp" />
From here I am not sure as to how to populate the spinner with data.
Upvotes: 3
Views: 919
Reputation: 10841
I want to populate a spinner with a list of strings from a table in my firebase database.
First, please make sure, you have retrieved the data correctly:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Database);
...
spinnerCategory = FindViewById<Spinner>(Resource.Id.spinnerCategory);
FirebaseApp.InitializeApp(this);
reference = FirebaseDatabase.Instance.Reference;
database = FirebaseDatabase.Instance;
if (reference != null)
{
//add value event listener to categories of your database.
reference.Child("categories").AddValueEventListener(this);
}
}
public void OnDataChange(DataSnapshot snapshot)
{
List<string> categories=RetrieveCategories(snapshot);
UpdateSpinner(categories);
}
private List<string> RetrieveCategories(DataSnapshot snapshot)
{
List<string> categories = new List<string>();
var children=snapshot.Children.ToEnumerable<DataSnapshot>();
HashMap map;
foreach (var s in children)
{
map = (HashMap)s.Value;
if (map.ContainsKey("categoryName"))
{
categories.Add(map.Get("categoryName").ToString());
}
}
return categories;
}
Notes: I upload data using HashMap, so when retrieving data, I also convert it back to hashmap.
Then create your UpdateSpinner
method to fill the SPinner:
private void UpdateSpinner(List<string> categories)
{
ArrayAdapter<string> adapter = new ArrayAdapter<string>(this, Resource.Layout.spinner_item_view, Resource.Id.text_item, categories);
spinnerCategory.Adapter = adapter;
}
And the Spinner
will be filled correctly:
Upvotes: 1