athos athos -4 years ago 134
Android Question

Spinner's onItemSelected callback called twice after a rotation if non-zero position is selected

When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the

onItemSelected
callback is called automatically during application initialization. What I find strange is that this happens twice when the device is rotated, causing me some problems that I will have to circumvent someway. This does not happen if the spinner initial selection is zero. I was able to isolate the issue, here's the simplest activity triggering it:

public class MainActivity extends Activity implements OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("Test","Activity onCreate");
setContentView(R.layout.activity_main);
((Spinner)findViewById(R.id.spinner1)).setSelection(2);
((Spinner)findViewById(R.id.spinner1)).setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> spin, View selview, int pos, long selId)
{
Log.i("Test","spin:"+spin+" sel:"+selview+" pos:"+pos+" selId:"+selId);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {}
}


And here's the logcat shown when the application is started and then the device rotated:

I/Test( 9881): spin:android.widget.Spinner@4052f508 sel:android.widget.TextView@40530b08 pos:2 selId:2
I/Test( 9881): Activity onCreate
I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2
I/Test( 9881): spin:android.widget.Spinner@40535d80 sel:android.widget.TextView@40538758 pos:2 selId:2


Is this the expected behaviour? Am I missing something?

Answer Source

Managed to find a solution in another stackoverflow question:

spinner.post(new Runnable() {
    public void run() {
        spinner.setOnItemSelectedListener(listener);
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download