I am trying to make a calculation with a button, after the user's input. When I don't fill the fields and press the button, my program crashes, but I just want to toast a message.. I have read a lot of other similar problems, but I don't understand what I have to do to fix in my code.. Is there anyone that can help me?? Thank you..
activity_main.xml:
<EditText
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="@+id/editText1"/>
<EditText
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="@+id/editText2"/>
<EditText
android:layout_width="130dp"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="@+id/editText3"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:id="@+id/textView1"/>
<Button
android:layout_width="65dp"
android:layout_height="wrap_content"
android:id="@+id/calculateButton
android:background="@android:drawable/ic_menu_edit" />
MainActivity.java:
......
mEditText1 = (EditText)findViewById(R.id.editText1);
mEditText2 = (EditText)findViewById(R.id.editText2);
mEditText3 = (EditText)findViewById(R.id.editText3);
mTextView = (TextView)findViewById(R.id.textView1);
cButton = (Button)findViewById(R.id.calculateButton);
cButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
......
public void calculate(){
Double value1 = Double.parseDouble(mEditText1.getText().toString());
Double value2 = Double.parseDouble(mEditText2.getText().toString());
Double value3 = Double.parseDouble(mEditText3.getText().toString());
if((value1!=0)&&(value2!=0)) {
if ((value1 != null) && (value2 != null) && (value3 != null)) {
calculatedValue = (value2 * value3) / value1;
mTextView.setText(calculatedValue.toString());}
else {
Toast.makeText(getApplicationContext(), "Please fill them all", Toast.LENGTH_LONG).show();
}
}
The error I get is:
12-22 20:09:26.694 18523-18523/com.example.nigi.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:248)
at java.lang.Double.parseDouble(Double.java:295)
at android.view.View.performClick(View.java:4442)
at android.view.View$PerformClick.run(View.java:18473)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5105)
Thank you!!
Use this code: