我正在尝试做什么:
我正在尝试创建一个Android应用,它可以在网格视图中创建多达6个不同的随机数。您可以使用简单的数字选择器调整设置。 我有2个nullPointerExceptions,我找不到要解决的问题:
如果dice = 1:“java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.TextView.setText(int)'”
如果dice =其他:“java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.GridLayout.addView(android.view.View)'”
这是我的代码的一部分:
public class MainActivity extends ActionBarActivity {
NumberPicker min = null;
NumberPicker max = null;
NumberPicker dice_amount = null;
int dice = 1;
int[] rng_numbers = new int[6];
TextView[] rng_number_fields = new TextView[6];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
GridLayout dicelayout = (GridLayout) findViewById(R.id.dice_layout);
switch (dice){
case 1:
//Numberpicker
min = (NumberPicker) findViewById(R.id.numberPicker_min);
min.setMaxValue(1000);
min.setMinValue(0);
min.setWrapSelectorWheel(false);
max = (NumberPicker) findViewById(R.id.numberPicker_max);
max.setMaxValue(1000);
max.setMinValue(0);
max.setWrapSelectorWheel(false);
dice_amount = (NumberPicker) findViewById(R.id.numberPicker_dice);
dice_amount.setMaxValue(6);
dice_amount.setMinValue(1);
dice_amount.setWrapSelectorWheel(false);
dice_amount.setValue(dice);
for(int i=0; i < dice; i++){
TextView myTextView = new TextView(this);
myTextView.setText("0");
myTextView.setWidth(100);
myTextView.setHeight(100);
dicelayout.addView(myTextView);
rng_number_fields[i] = myTextView;
}
etc...
}
public void OnButtonClick (View v){
Button button = (Button) v;
for( int k: rng_numbers ){
k = RollDice();
}
for(int l=0;l<6; l++){
rng_number_fields[l].setText(rng_numbers[l]);
}
}
如果您能告诉我我的错误以及如何改进此代码,那将是很棒的。
提前致谢! :d