I am creating a tip calculator app and I was wondering how I could allow my edittext (user enters bill amount) to still display the hint (hint says "Enter Bill Amount") but also internally have a default value of zero. The reason I would like to do this is because if they press the calculate tip buttons and there is no text inputted in the edittext the app force closes, and I think with a default value of zero that would solve my problems because it would just say tip $0.00. Alternatively if somebody could advise me on how to make a pop-up saying they need to enter a bill amount that would be even better!
Current Main Java:
package com.rockdrummer.calculating.calculating;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.text.NumberFormat;
import java.util.Locale;
public class MainScreen extends Activity {
private static final NumberFormat currencyFormat= NumberFormat.getCurrencyInstance();
Button ten, fifteen, twenty;
TextView tip;
EditText bill_amount;
double a = 0;
double b;
double af = 0;
double bf;
double ac = 0;
double bc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
initControls();
Locale.setDefault(Locale.US);
}
protected void initControls() {
ten = (Button) findViewById(R.id.bTen);
fifteen = (Button) findViewById(R.id.bFifteen);
twenty = (Button) findViewById(R.id.bTwenty);
tip = (TextView) findViewById(R.id.tip);
bill_amount = (EditText) findViewById(R.id.bill);
ten.setOnClickListener(new Button.OnClickListener() {
public void onClick(View ten) {
try {
calculate();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
fifteen.setOnClickListener(new Button.OnClickListener() {
public void onClick(View fifteen) {
try {
calculate_f();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
twenty.setOnClickListener(new Button.OnClickListener() {
public void onClick(View twenty) {
try {
calculate_t();
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
}
});
}
private void calculate() {
a = 0 + Double.parseDouble(bill_amount.getText().toString());
b = 0 + (a * 0.1);
tip.setText("You Should Tip " + currencyFormat.format(b));
}
private void calculate_f() {
af = 0 + Double.parseDouble(bill_amount.getText().toString());
bf = 0 + (af * 0.15);
tip.setText("You Should Tip " + currencyFormat.format(bf));
}
private void calculate_t() {
ac = 0 + Double.parseDouble(bill_amount.getText().toString());
bc = 0 + (ac * 0.20);
tip.setText("You Should Tip " + currencyFormat.format(bc));
}
}
Just check if the text is empty in your onClick/onCalculate method. If empty, use 0, ie:
public void onCalculate() {
float input = 0.0;
if (editText.getText().toString().equals("")) {
//Text is empty do nothing
} else {
//parse your value
input = Float.parseFloat(editText.getText().toString());
}
}