if statement problems in android
I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.开发者_开发问答RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it. Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString()
is there because the TextView will return a CharSequence
which may or may not be a String
.
Right now you are comparing the TextView itself to ""
, and not the String
it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException
that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText()
from a TextView
and not equals
a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.
精彩评论