gpt4 book ai didi

java - 当我不选择 RadioGroup 中的选项时,Android Studio-Quiz App 崩溃

转载 作者:行者123 更新时间:2023-11-29 02:31:21 25 4
gpt4 key购买 nike

我正在尝试解决我的 Android Quiz 应用程序中的问题。当我没有在我的 RadioGroup 中选择一个选项时,我的应用程序崩溃了: java.lang.CharSequence android.widget.RadioButton.getText()' 在空对象引用上

This is a part of my Java code:
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((capital.getCheckedRadioButtonId() == -1))
{
Toast.makeText(getApplicationContext(), "Select an Answer Please", Toast.LENGTH_LONG).show();
}
int selectid1 = capital.getCheckedRadioButtonId();
items = (RadioButton) findViewById(selectid1);
String s1 = items.getText().toString();
userAnswer1 = (RadioButton) findViewById(R.id.bucharest);
String theAnswer1 = userAnswer1.getText().toString();

if (s1.equals(theAnswer1)) {
score = score + 1;
}
Toast.makeText(MainActivity.this, "Your score is: " + score + " out of 6!", Toast.LENGTH_SHORT).show();
score = 0;
}
});
}
}

I also tried:


RadioButton bucharest;
RadioButton budapest;
RadioButton paris;

bucharest = (RadioButton) findViewById(R.id.bucharest);
budapest = (RadioButton) findViewById(R.id.budapest);
paris = (RadioButton) findViewById(R.id.paris);



if (bucharest.isChecked() || budapest.isChecked() || paris.isChecked()) {
Toast.makeText(MainActivity.this, "chosen", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Please select option", Toast.LENGTH_SHORT).show();

}

最佳答案

您收到 NullPointerException,可能在线

String s1 = items.getText().toString();

发生的事情是,如果没有选中单选按钮,您会显示 toast ,但随后还会执行 if block 之后的语句,当您选中单选按钮时,它会给出 null,您最终会在给出 NullPointerException 时调用 getText()。因此,将所有内容放在 if 之后的 else block 中。

关于java - 当我不选择 RadioGroup 中的选项时,Android Studio-Quiz App 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49494722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com