I am overriding onResume method to load previos state of my activity where it was ie spinner's last selected item etc. However the same code works fine for some activities but for some it causes crash as when i remove this onResume from them, Activity doesnt crash.
Here's the code
@Override
protected void onResume() {
super.onResume();
sp1 = (Spinner)findViewById(R.id.spinner);
sp2=(Spinner)findViewById(R.id.spinner1);
sp3=(Spinner)findViewById(R.id.spinner2);
sp4=(Spinner)findViewById(R.id.spinner3);
sp5=(Spinner)findViewById(R.id.spinner4);
TextView tx=(TextView)findViewById(R.id.upgradeResult) ;
SharedPreferences prefs = getSharedPreferences("restore_defensiveBuildings_state", Context.MODE_PRIVATE);
int spinner1Indx = prefs.getInt("spinner1_indx", 0);
int spinner2Indx = prefs.getInt("spinner2_indx", 0);
int spinner3Indx = prefs.getInt("spinner3_indx", 0);
int spinner4Indx = prefs.getInt("spinner4_indx", 0);
int spinner5Indx = prefs.getInt("spinner5_indx", 0);
sp1.setSelection(spinner1Indx);
sp2.setSelection(spinner2Indx);
sp3.setSelection(spinner3Indx);
sp4.setSelection(spinner4Indx);
sp5.setSelection(spinner5Indx);
tx.setText(""+totalAirBombUpgradeCost);
}
This is how i loaded items to the adapter
Spinner sp1;
Spinner sp2;
Spinner sp3;
Spinner sp4;
Spinner sp5;
TextView tx;
Button sbmt;
String levels[]={"Level 1",
"Level 2",
"Level 3",
"Level 4"
};
int[] images={R.drawable.giant_bomb_1and2,
R.drawable.giant_bomb_1and2 ,
R.drawable.giant_bomb_3and4,
R.drawable.giant_bomb_3and4
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_giant_bomb);
//// initialize all your visual fields
// if (savedInstanceState != null) {
// sp1.setSelection(savedInstanceState.getInt("MySpinner1", 0));
// // do this for each of your text views
// }
sbmt=(Button)findViewById(R.id.submit);
tx=(TextView)findViewById(R.id.upgradeResult);
sp1=(Spinner)findViewById(spinner);
sp2=(Spinner)findViewById(R.id.spinner1);
sp3=(Spinner)findViewById(R.id.spinner2);
sp4=(Spinner)findViewById(R.id.spinner3);
sp5=(Spinner)findViewById(R.id.spinner4);
SpinnerAdapterGiant adapter=new SpinnerAdapterGiant(this,levels,images);
sp1.setAdapter(adapter);
sp2.setAdapter(adapter);
sp3.setAdapter(adapter);
sp4.setAdapter(adapter);
sp5.setAdapter(adapter);
And this is the error
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
EDIT: When i remove onResume(), everything works fine app doesn't crash, just that it doesn't load activity's previous state.