dynamic – Populate spinner with years dynamically in Android?-ThrowExceptions

Exception or error:

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.

How to solve:

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);

###

I hope it will help you.

static final String[] Months = new String[] { "January", "February",
            "March", "April", "May", "June", "July", "August", "September",
            "October", "November", "December" };

 // Set years
        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.spinnerYears);
        spinYear.setAdapter(adapter);
        // Set months
        ArrayAdapter<String> adapterMonths = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, Months);
        adapterMonths.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        Spinner spinMonths = (Spinner)findViewById(R.id.spinnerMonths);
        spinMonths.setAdapter(adapterMonths);
        // Set days
        ArrayList<String> days = new ArrayList<String>();
        for (int i = 1; i <= 31; i++) {
            days.add(Integer.toString(i));
        }
        ArrayAdapter<String> adapterDays = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, days);

        Spinner spinDays = (Spinner)findViewById(R.id.spinnerDays);
        spinDays.setAdapter(adapterDays);

Leave a Reply

Your email address will not be published. Required fields are marked *