How to parse a double from EditText to TextView? (Android)

那年仲夏 提交于 2019-11-28 11:28:15
Vladimir Ivanov

Here is the JavaDoc for java.lang.Double class, parseDouble method:

/**
 * Parses the specified string as a double value.
 * 
 * @param string
 *            the string representation of a double value.
 * @return the primitive double value represented by {@code string}.
 * @throws NumberFormatException
 *             if {@code string} is {@code null}, has a length of zero or
 *             can not be parsed as a double value.
 * @since Android 1.0
 */

Empty values are not considered to be parseable. That's why you get this exception.

You can intoduce an additional check to your code to see if string in the noKids EditText is empty and if so, manually set the value to 0.0:

noKidsStr = noKids.getText().toString();

if(noKidsStr == null || noKidsStr.isEmpty()) {

  etKids = 0.0;

} else {

  etKids = Double.parseDouble(noKids.getText().toString());

}

I suggest writing some sort of convenience utility method that you can re-use for all similar situations in the future.

you should wrap the Double.parseDouble.. statements in a try/catch clause, to catch any NumberFormatExceptions, and set other values where they fail

edit:

try{
    etKids = Double.parseDouble(noKids.getText().toString());
} catch (final NumberFormatException e) {
    etKids = 1.0;
}
try{
    etGumballs = Double.parseDouble(noGumballs.getText().toString());
} catch (final NumberFormatException e) {
    etGumballs = 1.0;
} 

Two things you can do: First, only allow numeric data in your EditText field. Actually, I see you already did that. I usually use android:numeric - this is the first I've seen of android:inputType. Thanks for that. =)

Second, ensure that you have text in your EditText with a simple check.

if(noKids.getText().length() > 0)
{
    etKids = Double.parseDouble(noKids.getText().toString());
}

This is a java question, not an android question.

You should handle the NumberFormat exception in your code. What happens if somebody enters "abc" into the text box? What do you want your app to do? You handle exceptions using try/catch blocks: http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html

You might also want to check if noKids.getText().toString() is empty before trying to convert it. It might make sense for there to be a different feedback to the user if the string is "" vs if the string is "abc".

private void calculate() {
         try{
            etKids = Double.parseDouble(noKids.getText().toString());
            etGumballs = Double.parseDouble(noGumballs.getText().toString());
            tvSumIn = etGumballs / etKids; 
          }catch(exception e)
          {
            e.printStackTrace():
          }    
        String thisIsIt = new Double(tvSumIn).toString();

            if(tvSumIn < 2){
                noSum.setText(thisIsIt + " This is it ");
            }else{
                noSum.setText("This is else");
            }

        }

Another improvement:

String thisIsIt = new Double(tvSumIn).toString();

if(tvSumIn < 2){
    noSum.setText(thisIsIt + " This is it ");
}else{
    noSum.setText("This is else");
}

could be:

if(tvSumIn < 2){
    noSum.setText(tvSumIn + " This is it ");
}else{
    noSum.setText("This is else");
}

Then you don't have to create a useless String

I think the best way to check if the value is correct is as follows:

   noKidsStr = noKids.getText().toString();

   try
   {
      etKids = Double.parseDouble(noKids.getText().toString());
   }
   catch (NumberFormatException e)
   {
      //Here request a valid value
      Toast.makeText(getBaseContext(), "value is not valid", Toast.LENGTH_LONG).show();
      noKids.requestFocus();
      return;

      //Or you can add a value

    }
}

I think this method is more elegant and takes into account any kind of input they add. BR, Adrian.

Try this code TextView_object.setText(new Double(sum).toString());

Extending on Vladmir's post (I cannot add a comment to that specific one)

you can have a short hand of that using the following two lines instead of the if/else block (? is the equivalent of if/else, when used in certain situations)

noKidsStr = noKids.getText().toString();

etKids = (noKidsStr == null || noKidsStr.isEmpty())?0.0:Double.parseDouble(noKids.getText().toString());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!