私は、自分のアクティビティ、すなわちスピナーの最後に選択されたアイテムなどのprevios状態を読み込むためにonResumeメソッドをオーバーライドしています。しかし、同じコードはいくつかのアクティビティでうまく動作しますが、これらからonResumeを削除してください。アクティビティがクラッシュしません。onResumeメソッドはActivityをクラッシュさせます
ここではこれは私がアダプタ
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);
にアイテムをロードする方法であり、これは誤り
java.lang.ArrayIndexOutOfBoundsException: length=4; index=4
EDITあるコード
@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);
}
です:私はonResumeを(削除)すべて正常に動作しますが、アプリケーションはクラッシュしません。アクティビティの以前の状態はロードされません。
にご使用のアレイサイズを大きく 5つのスピナーを持っていますあなたのリストに。配列は常に0から始まります。あなたのエイリアスは0から3までです。配列内に4番目のインデックスがありません –
[何がjava.lang.ArrayIndexOutOfBoundsExceptionを引き起こすのですか? //stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Selvin
各スピナーに4つのアイテムを追加しています@SaurabhBhandari –