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

I am really starting to learn Java. When I run this code, everything works fine until I leave my EditText fields in an empty field and hit the start button. Then I get:

ERROR/AndroidRuntime(866): FATAL EXCEPTION: main ERROR/AndroidRuntime(866): java.lang.NumberFormatException: ERROR/AndroidRuntime(866): at org.apache.harmony.luni.util.FloatingPointParser.parseDouble(FloatingPointParser.java:267) 

I think when I try to parse Double from a string, it does not get any value and creates an error. I was wondering how to avoid this error and give some kind of variable value so that it is never empty? Thanks for the help!

 import android.app.Activity; import android.os.Bundle; import android.widget.EditText; import android.widget.TextView; import android.widget.Button; import android.view.View; import android.view.View.OnClickListener; public class Main extends Activity { private EditText noKids; private EditText noGumballs; private TextView noSum; private Button b; private Button br; double etKids = 0; double etGumballs = 0; private double tvSumIn = 0.00; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initControls(); } private void initControls() { noKids = (EditText) findViewById(R.id.xetKids); noGumballs = (EditText) findViewById(R.id.xetGumballs); noSum = (TextView) findViewById(R.id.tvSum); br = (Button) findViewById(R.id.xbtnReset); br.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { reset(); br.setVisibility(View.INVISIBLE); } private void reset() { noKids.setText(""); noGumballs.setText(""); noSum.setText(""); } }); b = (Button) findViewById(R.id.xbtnCalculate); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { calculate(); br.setVisibility(View.VISIBLE); } private void calculate() { etKids = Double.parseDouble(noKids.getText().toString()); etGumballs = Double.parseDouble(noGumballs.getText().toString()); tvSumIn = etGumballs / etKids; String thisIsIt = new Double(tvSumIn).toString(); if(tvSumIn < 2){ noSum.setText(thisIsIt + " This is it "); }else{ noSum.setText("This is else"); } } }); } } 

This is my main.xml file and I assume that there is nothing special in the manifest.

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="How many kids have you got?"></TextView> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:id="@+id/xetKids"> <requestFocus></requestFocus> </EditText> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="How many gumballs have you got?"></TextView> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" android:id="@+id/xetGumballs"></EditText> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Calculate" android:id="@+id/xbtnCalculate"></Button> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tvSum"></TextView> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/xbtnReset" android:text="Reset" android:onClick="selfDestruct" android:visibility="invisible"></Button> </LinearLayout> 
+4
source share
9 answers

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

 /** * 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 parsed. That is why you get this exception.

You can enter an additional check in your code to see if the line in 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 convenient utility method that you can reuse for all such situations in the future.

+14
source

you must wrap the Double.parseDouble .. statements in the try / catch clause to catch any NumberFormatExceptions and set other values ​​in which 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; } 
+4
source

Two things you can do: First, allow only numeric data in the EditText field. In fact, I see you have already done this. I usually use android: numeric - this is the first thing I saw in android: inputType. Thanks for this. =)

Secondly, make sure you have text in EditText with a simple check.

 if(noKids.getText().length() > 0) { etKids = Double.parseDouble(noKids.getText().toString()); } 
+2
source
 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"); } } 
+1
source

This is a Java question, not an Android question.

You must handle the NumberFormat exception in your code. What happens if someone enters "abc" in a text box? What do you want from your application? You handle exceptions using try / catch blocks: http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html

You can also check for noKids.getText (). toString () is empty before trying to convert it. Perhaps it makes sense to feedback with the user if the string is "", if the string is "abc".

0
source

Another improvement:

 String thisIsIt = new Double(tvSumIn).toString(); if(tvSumIn < 2){ noSum.setText(thisIsIt + " This is it "); }else{ noSum.setText("This is else"); } 

may be:

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

Then you do not need to create a useless string

0
source

I think the best way to verify the value is correct:

  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 input they add. BR, Adrian.

0
source

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

0
source

Continued on post by Vladmir (I can not add a comment to this specific)

you may have a short hand 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()); 
0
source

All Articles