hybrid94 hybrid94 - 9 days ago 5
Android Question

Android Studio onClick Set Text issue

I'm trying to create an MPG conversion where the user enters their amount of miles as an integer and their amount of liters they have topped up their car by as a double. A

submit
button click will divide miles by litres and provide me with an MPG figure.

My Code:

final EditText mileage = (EditText) findViewById(R.id.Mileage);
final EditText litres = (EditText) findViewById(R.id.litres);
final Button mpg = (Button) findViewById(R.id.submit_MPG);
final TextView result = (TextView) findViewById(R.id.mpg_result);

mpg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer miles = Integer.parseInt(mileage.toString());
Double litre = Double.parseDouble(litres.toString());
Double answer = Double.parseDouble(result.getText().toString());

answer = miles / litre;

result.setText(answer);
}
});


My issue is that I'm struggling to convert the user input into doubles and integers and then setting the result to a textview.

My AC:


  • To be able to convert miles and liters into an MPG figure.



Thank you in advance!

Answer

The problem is that you aren't actually converting:

public void onClick(View v) {
    int miles = Integer.parseInt(mileage.getText().toString());
    double litre = Double.parseDouble(litres.getText().toString());
    double answer = (double)miles / litre;

    result.setText((""+answer));
    ...

Here, I convert with (double)miles / litre and then set the TextView text to be the answer.