Search code examples
javaandroidspinnerlifecycle

Android spinner not retaining value when activity is changed (lifecycle related)


In my activity, I have a Spinner and a ListView. The Spinner is used to filter the items in the ListView. When the user clicks on a list item, another activity is called, which shows the details of the list item. Then, from the details activity, the user presses the back button, and the spinner (thus the the list) gets reset to its initial value.

This is due to the fact that I populate the spinner's adapter, and declare its onItemSelectedListener, into the onStart() method, which is called again when the user presses the back button. Also the onItemSelectedListener is actually called once by the onStart() method.

How do I avoid this behavior? I guess I should move the listener and the adapter somewhere else, but where?

Here is an overview of the class

public static ArrayList<String> years;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.archive);

    // populate years array here
}

@Override
protected void onStart()
{
    super.onStart();

    Spinner spinner = (Spinner) findViewById(R.id.spinner_anni);

    // create spinner adapter
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, ArchiveActivity.years);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    // create spinner listener
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        @Override
        public void onItemSelected(AdapterView<?> parentView,
                View selectedItemView, int position, long id)
        {
            filterList(ArchiveActivity.years.get(position));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView)
        {
            return;
        }
    });

    // create list listener
    ListView list = (ListView) findViewById(R.id.list_archive);
    list.setOnItemClickListener(this);
}

private void filterList(String year)
{
    // filter list data here
}

@Override
public void onItemClick(AdapterView<?> list, View item, int pos, long id)
{
    // call detail activity for list item that's been pressed
    Intent i = new Intent(this, DetailActivity.class);
    startActivity(i);
}

Solution

  • Normally you initiated the spinner and the adapter in the onCreate() method. Furthermore you have to save the status of you spinner and recreate it when the activity comes back to the foreground. Check this question on how to save the application state.