In my application, I have a Spinner whose onItemSelected initializes the value of a class member, say, a, to its default value of 0. The user may then perform steps to change the value of a. I am saving the value of a in onSaveInstanceState and restoring it in onRestoreInstanceState. However, apparently as a result of restoring of the Spinner, its onItemSelected gets called and puts a back to zero. I want the value entered by the user to be preserved.
Note, however, that the old value of a would not make sense in any other setting of the Spinner (hence zeroing it upon item selection). Unfortunately, it is also hard to validate it. So, not knowing that the call to onItemSelected was fake, putting a to zero is inevitable.
The problem is that the input event handler seems to be put into some queue and called after onCreate / onRestoreInstanceState is finished (twice, which is another thing I don’t understand). My question thus is, at what moment should I restore a to the non-default value from the saved instance state? Should I put this task at the end of the input event queue somehow? Or is there a way of distinguishing whether the call of onItemSelected happened as a result of an actual user input or just instance state restoration?
Code example:
private String KEY = "(...).A";
private int a;
public void onItemSelected(AdapterView<?> parentView, View childView, int position, long id) {
/* other important stuff */
a = 0;
Log.d("info", "a zeroed");
}
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putInt(KEY, a);
}
public void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
a = state.getInt(KEY, a);
Log.d("info", "a restored");
}
After a change of orientation, the log says
info a restored
info a zeroed
info a zeroed
Here’s what I came up with so far. It does the trick without counting off two calls of
onItemSelectedfound by a mere observation. However, I still consider it a workaround:After a change of orientation, the log now says
The bad thing about this solution is that
ahas its value in the time when theSpinneris still uninitialized, which does not cause problems at the time being, but should never happen. A proper solution should letonItemSelecteddo all of its work and setaafter that.