WAQAR ALAM WAQAR ALAM - 4 years ago 89
Android Question

tip calculator crased when call to calculate

My code is:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText amt = (EditText) findViewById(R.id.bill_amt);
final EditText tip = (EditText) findViewById(R.id.bill_per);
final TextView result = (TextView) findViewById(R.id.res);

Button calc = (Button) findViewById(R.id.button1);
calc.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
double amount = Double.parseDouble(amt.toString());
double tip_per = Double.parseDouble(tip.toString());
double tip_cal = (amount * tip_per) / 100;
result.setText("Result : " + Double.toString(tip_cal));
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

}


please correct the error shown in this coding
android studio is also showing warning on Result.text
something about 'use resource string with placeholder'

i'm following this webpage's tutorial

Answer Source

You are tying to parse EditText into Double Error -amt.toString() and tip.toString(). Which is incorrect(Not Possible at all).

Replace this:

double amount = Double.parseDouble(amt.toString());
double tip_per = Double.parseDouble(tip.toString());

With this:

double amount = Double.parseDouble(amt.getText().toString());
double tip_per = Double.parseDouble(tip.getText().toString());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download