Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DecimalFormat Problem throws a StackOverFlowError?

Tags:

java

android

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) {
            }
        });  
like image 475
Praveen Avatar asked Feb 04 '26 02:02

Praveen


1 Answers

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.

like image 52
Tomas Narros Avatar answered Feb 06 '26 14:02

Tomas Narros