Bharthish Athreya Bharthish Athreya - 2 months ago 5
Java Question

Why 'Res' Variable holding some Random numbers instead of retrieving the number from edit text field?

Below is the code:

public class MainActivity extends AppCompatActivity implements
View.OnClickListener {

private TextView TvTtlCrd;


int Res = TvTtlCrd.getText().length();
switch (view.getId()) {
case R.id.btnCal:
try {
Float Calculation = (
(Float.parseFloat(numM1) * Float.parseFloat(numP1))
+(Float.parseFloat(numM2)*Float.parseFloat(numP2)));
Float Result=Calculation/Res;
TvRes.setText(String.valueOf(Result));
} catch (Exception e) {
TvRes.setText("Make sure to Enter all the fields");
}
break;
}
}
}


When I debug the code I found that all variables retrieve the same number as in text field but the TvTtlCrd text field value is not retrieved. What is the reason?
I have posted only part of the code which is relevant.
also How to Store variables in List and calculate using list functions?
Thanks

Answer

It appears that you are grabbing the length of the TvTtlCrd Object instead of the Text.

Change:

int Res = TvTtlCrd.getText().length();

To:

int Res = Integer.parseInt(TvTtlCrd.getText().toString());

Or: and parse however you see fit to get the int value.

String Res = TvTtlCrd.getText().toString();