尝试从“编辑”文本中获取值并变为双精度时Android应用程序崩溃

时间:2017-06-20 01:00:29

标签: android

我是android studio的新手,java对我来说很新鲜。我正在尝试制作转换应用。为此,我必须获取编辑文本框的值并将其转换为数字。当我的应用程序崩溃时,我添加的那一刻:

double n1Var = Double.parseDouble(n1.getText().toString());

我的应用会打开,然后立即关闭。如果我删除它,该应用程序工作正常。我尝试了不同的方式把它变成一个双,尝试甚至把它变成一个整数仍然无法正常工作。如果我尝试一下它就可以了。

4 个答案:

答案 0 :(得分:1)

//assuming that (EditText)n1 = (EditText)findViewById(R.id.id_of_n1);

String et_val = n1.getText().toString().trim();
double n1Var;

if(et_val.equals("") || et_val.length==0 ){

/*you can improve on this filter with a regex to check if the content of the edit text is event a number. 

Furthermore, you can also control the entry of the information allowed into edit text with a switch in the xml for the edit text by allowing for only entry of numbers.

You can also do control the entry into the edit text with a java code that would compel the user to only enter numbers if that complies with what you are looking forward to executing with the user.

*/ 
    n1Var = 0;

}else{
    n1Var = Double.parseDouble(et_val);
}

//希望这有帮助。干杯和快乐的编码。

答案 1 :(得分:0)

从Java Documentation,以下是可以从 <Picker Title="Privacy" ItemsSource="{Binding Privacies}" SelectedItem="{Binding Privacy}" ItemDisplayBinding="{Binding Name}"/> 抛出的异常:

  

抛出:

     

NullPointerException - 如果字符串为null

     

NumberFormatException - 如果字符串不包含可解析的double。

根据您的描述,可能会抛出Double.parseDouble。检查logcat以确切了解引发的异常。

答案 2 :(得分:0)

似乎什么都没有用。这是我的代码+当我按下按钮打开双人活动时的日志...

Log screenshot

EditText ETInput;
Button BConvert;
TextView TVresult;
RadioButton c2f;
RadioButton c2k;
RadioButton f2c;
RadioButton f2k;
RadioButton k2c;
RadioButton k2f;

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_converter);


   ETInput = (EditText)findViewById(R.id.ETInput);
    double a = Double.parseDouble(ETInput.getText().toString());
   BConvert = (Button)findViewById(R.id.BConvert);
   TVresult = (TextView)findViewById(R.id.TVresult);
   c2f = (RadioButton)findViewById(R.id.c2f);
   c2k = (RadioButton)findViewById(R.id.c2k);
   f2c = (RadioButton)findViewById(R.id.f2c);
    f2k = (RadioButton)findViewById(R.id.f2k);
    k2c = (RadioButton)findViewById(R.id.k2c);
    k2f = (RadioButton)findViewById(R.id.k2f);




    String val = ETInput.getText().toString().trim();
    double var;
    var = Double.parseDouble(val);




}

}

答案 3 :(得分:0)

用这个:

双w;

    try {
        w = new Double(input.getText().toString());
    } catch (NumberFormatException e) {
        w = 0;
    }

w始终为零