初始化Hello
上的EditTexts
返回一个“”,它无法转换为有效的double,因此会出现此错误。使用显式值可能会有所帮助,但之后我将丢失onCreate
文本。
如何解决此问题而不会丢失android:hint
文字?
android:hint
Code
public class MainActivity extends Activity {
private double quant, problem, verbal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText quantScore = (EditText) findViewById(R.id.quant);
EditText problemScore = (EditText) findViewById(R.id.problem);
EditText verbalScore = (EditText) findViewById(R.id.verbal);
Button calculate = (Button) findViewById(R.id.button);
quant = Double.valueOf(quantScore.getText().toString());
problem = Double.valueOf(problemScore.getText().toString());
verbal = Double.valueOf(verbalScore.getText().toString());
final double total = quant + problem + verbal;
calculate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "The total is " +total, Toast.LENGTH_LONG).show();
}
});
}
Layout
答案 0 :(得分:1)
您应该捕获NumberFormatException并提供所需的默认值。
try {
quant = Double.valueOf(quantScore.getText().toString());
} catch(NumberFormatException e) {
quant = 0;
}
这不适用于EditText
为空时无法解析为 Double 的任何文字。