0

I want to take the depth input by the user and mathematically operate on it to obtain cost and then display it to the user. How do I go about doing that?(If didn't notice already, I don't know Java). Thanks.

 private void estimateCost(View view){
        EditText depth = findViewById(R.id.depth);
        TextView cost = findViewById(R.id.cost);
        String x = depth.getText().toString().trim();
        cost.setText(x);
    }
Ajay Bhargav
  • 7
  • 1
  • 4

3 Answers3

2

You need to parse your String obtained from EditText, then perform some operations.

 private void estimateCost(View view){
    EditText depth = findViewById(R.id.depth);
    TextView cost = findViewById(R.id.cost);

    String x = depth.getText().toString().trim();  

    // parse to a number, i.e. int
    int depthValue = Integer.parseInt(x);

    // calculate total cost
    int totalCost = ...

    cost.setText(String.valueOf(totalCost));
}
canihazurcode
  • 252
  • 2
  • 9
0

You can create a button to obtain the value. For example:

<Button
        android:id="@+id/bt_calc"
        android:text="calc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Then you can catch the click event (put it inside onCreate method):

EditText depth = (EditText) findViewById(R.id.depth);
TextView cost = (TextView) findViewById(R.id.cost);
Button btCalc = (Button) findViewById(R.id.bt_calc);
int costValue;

btCalc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //in here you can

            //get the depth from the EditText:
            int depthValue = Integer.valueOf(depth.getText().toString());

            //do the operations (example):
            costValue = depthValue + 1;

            //and display the cost in the TextView:
            cost.setText(String.valueOf(costValue));
        }
});

Good luck!

gbruscatto
  • 686
  • 7
  • 21
0

If your input contains letters as well you won't get int from it with Integer.parseInt()

Use this

int x = 0;
for (int i=0; i < str.length(); i++) {
    char c = s.charAt(i);
    if (c < '0' || c > '9') continue;
    x = x * 10 + c - '0';
}
Rainmaker
  • 10,294
  • 9
  • 54
  • 89