Search code examples
javaandroidxmltextwatcherandroid-textwatcher

IF statement doesn't work with TextWatcher


My code looks simple and I don't know what is the problem. If I code something like this:

tvResult.setText(sum+ "RUB");

it shows correct numbers. But if I try to add an IF statement like this:

if(sum>=114000) {
                    tvResult.setText(sum + " RUB");
                }

and sum equals, say, 1000000, it shows weird number: 1111111.0. Need your advice =) Thanks in advance

Here is the XML code:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:id="@+id/tvCash"
        android:layout_below="@id/tvCalculate"
        android:hint="@string/cash_money"
        android:background="@drawable/zakat_red"
        android:layout_marginTop="20dp"/>

    <EditText
        android:layout_width="130dp"
        android:layout_height="40dp"
        android:id="@+id/etCash"
       android:inputType="numberDecimal"
        android:layout_above="@+id/tvBank"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="@string/hint_zakat"
        android:gravity="end"
        android:imeOptions="actionDone"/>

And Java code:

TextWatcher twCash=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvCash.setBackgroundResource(R.drawable.zakat_green);
                sum+=Float.valueOf(etCash.getText().toString());
                if(sum>=114000) {
                    tvResult.setText(sum + " RUB");
                }
            }
        };

Solution

  • There is problem with your logic. As you are using TextWatcher, to compute the sum of all the numbers entered in your editText, even if you type '.' after any number , afterTextChanged() will get invoked and then it will add that number to the aggregated sum.So let's say , you input the following characters consecutively : 2 , 3, . , 4 , 7 Then you will get the sum = 94.87 And I guess this is not the correct way to compute the sum of the numbers entered. You have to correct your logic to get the desired output.