I have a Spinnerin my Activity and I define an OnItemSelectedListener in OnResume:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view,
int pos, long id) {
final String newLanguage = iconAdapter.getItem(pos).name();
Helper.getSettings(view.getContext()).setLocale(newLanguage);
setLocale(new Locale(newLanguage));
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Now, onItemSelected gets called twice during the creation of the activity - without the user selecting anything. The first time everything works as intended, but the second time view is null and a NullPointerException is thrown.
onItemSelected called at all, when no user selected an item?null?Edit:
So this code happens BEFORE setOnItemSelectedListener:
spinner = findViewById(R.id.language_spinner);
LanguageSpinnerAdapter iconAdapter = new LanguageSpinnerAdapter(this, Arrays.asList(LanguageIconEnum.values()));
spinner.setAdapter(iconAdapter);
String language = Helper.getSettings(this).getLocale();
if(language == null){
spinner.setSelection(0);
} else {
switch (language) {
case "de":
spinner.setSelection(1);
break;
case "fr":
spinner.setSelection(2);
break;
default:
spinner.setSelection(0);
}
}
"Am I right to assume, the two times the OnItemSelected is called, is when I set the adapter and then when I call .setSelection() manually?" - That's not the case, if I delete the manual setSelection() part, it's still called twice.
The function setLocale() calls recreate which populates the spinner again, so that's where the second call to OnItemSelectedcomes from.
So what's left:
view = null?Ok, here the answers:
1) Why is onItemSelected called at all, when no user selected an item?
OnItemSelected is called.2) Why twice?
OnItemSelected (in setLocale) I call recreate, which populates the spinner a second time.3) Why is the view the second time null?
Solution was:
if(lastPos != -1 && lastPos != pos){
final String newLanguage = iconAdapter.getItem(pos).name();
Helper.getSettings(view.getContext()).setLocale(newLanguage);
setLocale(new Locale(newLanguage));
}
lastPos = pos;
Anybody knows the answer to question 3?