I'm very beginner to programming in android. Sorry if my question is obvious.
I have an editText with inputType="numberDecimal". I watch it's changes with TextWatcher, calculating from it's value (Double type), and show it on a TextView. The calculation is OK, except if the editText has the value ".". If the editText has the value ".", the program drops an error (force close).
My question is: how can I set the editText value to "0." with the use of addTextChangedListener if the editText gets the value "."? Have You got for this situacion a best practice? Thanks in advance for Your help.
My code is:
public class ConversionsFragment extends Fragment{
private EditText etDistBase;
private TextView tvMeterResult;
private TextView tvKmResult;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_conversions, container, false);
etDistBase = (EditText) rootView.findViewById(R.id.textEdit_conv_distance);
tvMeterResult = (TextView) rootView.findViewById(R.id.conv_dist_result_meter);
tvKmResult = (TextView) rootView.findViewById(R.id.conv_dist_result_km);
etDistBase.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
calculateConvDistances();
}
});
return rootView;
}
private void calculateConvDistances() {
String baseText = etDistBase.getText().toString();
Double baseValue = 0.0,
meterResult = 0.0,
kmResult = 0.0;
// if (baseText == ".") {
// etDistBase.setText("0.");
// baseText = "0";
// }
if (baseText.length() == 0)
baseText = "0";
if (baseText != null) {
baseValue = Double.parseDouble(baseText);
meterResult = baseValue * 1000;
kmResult = baseValue;
} else {
meterResult = 0.0;
kmResult = 0.0;
}
tvMeterResult.setText(Double.toString(meterResult));
tvKmResult.setText(Double.toString(kmResult));
}
}
Try with this
write into the
afterTextChanged()
method.