DecimalFormat Problem throws a StackOverFlowError?
I have a edit text. i want to enter the decimal values in it.
that is when i have enter a first number. it should be like this: .01
then i have enter a second number. it should be like this: .12
then for third one. it should be like this: 1.23
it will go like this.... how to implement this scenario in the Android Platform. Any Idea?
Edit:
I have tried this.But i got the StackOverFlowError when i am appending the string into the EditText. i have posted my code below:
amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
try {
if (s.length() == 1) {
Float f = Float.parseFloat(s.toString()) / 100;
System.out.println(String.valueOf(f));
amount.setText("");
amount.append(String.valueOf(f));//getting stackoverflow error here
} else if (s.length() > 1) {
String str = s.toString().replace(".", "");
Float f = Float.parseFloat(str) / 100;
System.out.println(String.valueOf(f));
amount.setText("");
amount.append(String.valueOf(f));
}
} catch (Exception e) {
}
}
public void beforeTextChanged(CharSequence s, int start, int count,开发者_开发知识库
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
Look, you are implementing a TextChangedKListener for an element, in which you are changing the element text.
So, in this lines
amount.setText("");
amount.append(String.valueOf(f))
your TextWatcher implementation is being called (as you can see here and here).
As you can see on the second link, the API doc for the afterTextChanged
method, warns you about the risk of getting into infinite loops:
be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively
The self afterTextChanged description, on the TextWatcher API doc, recommends a workaround for handling with this:
You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can use setSpan(Object, int, int, int) in onTextChanged(CharSequence, int, int, int) to mark your place and then look up from here where the span ended up.
精彩评论