Populate spinner with years dynamically in Android?

colmulhall picture colmulhall · Apr 10, 2013 · Viewed 29k times · Source

I have been racking my brain trying to get this to work. I want to dynamically enter in years from 1900 to the current year into a spinner. I don't think that this is possible to do using an XML defined array but can I do it with an array adapter? Here is what I have so far:

ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);

for (int i = 1900; i <= thisYear; i++) 
{
    years.add(i);
}

adapter = new ArrayAdapter<String>(this, 
           android.R.layout.simple_spinner_item, years);

//spinner to enter this list to
spinYear = (Spinner)findViewById(R.id.yearspin);

Here's the XML for the spinner:

<Spinner
        android:id="@+id/yearspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

Thanks for any help.

Answer

vincentjames501 picture vincentjames501 · Apr 10, 2013

You're very close. Try this:

ArrayList<String> years = new ArrayList<String>();
int thisYear = Calendar.getInstance().get(Calendar.YEAR);
for (int i = 1900; i <= thisYear; i++) {
    years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);

Spinner spinYear = (Spinner)findViewById(R.id.yearspin);
spinYear.setAdapter(adapter);

You just forgot to add

spinYear.setAdapter(adapter);