1

There are 3 EditText, 1st Price input,2nd Percentage, 3rd Result. I am trying to calculate EditText inputs using onFocusChangeListener. The Code:

etPercen.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (!hasFocus) {
                    OnFocusChangedPercenCalculator();
                }
            }
        });

        etresult.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (!hasFocus) {
                    OnFocusChangedResultCalculator();
                }
            }
        });

and

public void OnFocusChangedPercenCalculator() {
        String text1 = String.valueOf(etPrice.getNumericValue()).toString();
        String text2 = etPercen.getText().toString();
        String text3 = String.valueOf(etresult.getNumericValue()).toString();
        double input1 = 0;
        double input2 = 0;
        int i = 0;
        if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
            input1 = Double.parseDouble(text1);
        input2 = Double.parseDouble(text2);

        if (text1.length() != 0 ){
            if(text2.length() != 0) {
                double output = (input1 * input2) / 100;
                e = String.valueOf(output);
                etresult.setText("" + e);
            } else if (text2.length() ==0 || text2.matches("")){
                etresult.setText(i+"");
            }
        }else if(text1.length() == 0){
            if(text2.length() != 0) {
                etresult.setText(i+"");
        } else if (text2.length() ==0 || text2.matches("")){
            etresult.setText(i+"");
        }
        }
    }

    public void OnFocusChangedResultCalculator() {
        String text1 = String.valueOf(etPrice.getNumericValue()).toString();
        String text2 = etPercen.getText().toString();
        String text3 = String.valueOf(etresult.getNumericValue()).toString();
        double input1 = 0;
        double input3 = 0;
        int i = 0;
        if (text1.length() > 0 || text2.length() > 0 || text3.length() > 0)
            input1 = Double.parseDouble(text1);
        input3 = Double.parseDouble(text3);

        if (text1.length() != 0 ){
            if(text3.length() != 0) {
                double output = (input3 / input1) * 100;
                e = String.valueOf(output);
                etPercen.setText("" + e);
            } else if (text3.length() ==0 || text3.matches("")){
                etPercen.setText(i);
            }
        }else if(text1.length() == 0){
            if(text3.length() != 0) {
                etPercen.setText(i);
        } else if (text3.length() ==0 || text3.matches("")){
            etPercen.setText(i);
        }
        }else if (input3 > input1){
            etPercen.setText(100);
        }
    }

What i want to do is 2nd and 3rd EditTexts looking each other. I mean when the user change focus from 2nd/3rd editText then the calculation will begin in an instant. The idea is to make the 2nd one calculate and put the result on the 3rd and make the 3rd one calculate and put the result on 2nd. It depends on the user if he/she wants to change fill/change the value (lets say the price is 10000, the user want to know whats the 20% of it, or the user want the other way around, whats the % of 20000 from 10000). Thats my expectation, but when we emptied the 1st and 3rd edittext the output of the 2nd one will be NaN. How to handle this? i mean avoid the result become NaN?

Jedi Fighter
  • 377
  • 1
  • 4
  • 20
  • Other than NaN, is the interaction giving correct result ? – inmyth Apr 16 '15 at 04:59
  • yes, when there is a value the calculation runs perfectly .EDIT: i mean there are values on these three EditTexts – Jedi Fighter Apr 16 '15 at 05:03
  • i mean there are values on these three EditTexts , EDIT: two i mean.Gosh My head is overflowing – Jedi Fighter Apr 16 '15 at 05:10
  • 1
    The whole logic seems unduly complicated to me. Why don't you just get these 3 strings, `trim()` them, check each if the `text.length()>0`? If yes - parse it to double, if not - set to 0. 6-9 lines max, without multilevel `if`s. – AndroidEx Apr 16 '15 at 05:14
  • i am a bit confuse with some conditions, i mean what to use Greater than zero or Not equal to zero . BTW i am on workload trying JSON parse store to database, handling layouts and etc(cant think clearly right now). If you could give an example i'll highly appreciate it – Jedi Fighter Apr 16 '15 at 05:20
  • did you mean String.valueOf(etPrice.getNumericValue()).toString().trim(); ? – Jedi Fighter Apr 16 '15 at 05:24
  • Sorry, didn't mean any offense. `String text1 = etPrice.getText().toString().trim(); double number1 = text1.length()>0?Double.parseDouble(text1):0;` – AndroidEx Apr 16 '15 at 05:27
  • @Android777 oh i get it, in an IF that checks text.length > 0 we parse and do the calculation, else setText to zero. – Jedi Fighter Apr 16 '15 at 05:30
  • I suspect you were getting the error because of not trimming, and " " case was passing through all the conditions unnoticed until the moment of parsing. – AndroidEx Apr 16 '15 at 05:32
  • no worries,none taken.. just want to make sure----->double number1 = text1.length()>0?Double.parseDouble(text1):0; <--- means if double number1 lenght is > 0 then number1 = parseDouble of text1 , else number1 = 0 ? right? – Jedi Fighter Apr 16 '15 at 05:34
  • To make it more readable, it's absolutely equivalent to: `double number1; if (text1.legth() > 0) { number1 = Double.parseDouble(text1);} else { number1 = 0; }` – AndroidEx Apr 16 '15 at 05:37
  • Eventually, I refactored the second method a little bit for illustration, I may have missed some mathematical conditions but overall I think it should work. – AndroidEx Apr 16 '15 at 05:47

3 Answers3

2

Ok, I refactored the second method to illustrate what I was talking about. Should be working.

      public void OnFocusChangedResultCalculator() {
        String text1 = etPrice.getText().toString().trim();
        String text2 = etPercen.getText().toString().trim();
        String text3 = etresult.getText().toString().trim();
        double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
        double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;

        if (input3 > input1){
            etPercen.setText(100);
            return;
        }

        double output = (input3 / input1) * 100;
        etPercen.setText(output);
    }

UPDATE

public void OnFocusChangedResultCalculator() {
        String text1 = String.valueOf(etPrice.getNumericValue()).toString().trim();
        String text2 = etPercen.getText().toString().trim();
        String text3 = String.valueOf(etresult.getNumericValue()).toString().trim();
        double input1 = text1.length()>0 ? Double.parseDouble(text1) : 0;
        double input3 = text3.length()>0 ? Double.parseDouble(text3) : 0;

        if (input3 > input1){
            etPercen.setText(Integer.toString(100));
            etresult.setText(Double.toString(input1));
            return;
        }

        double output = (input3 / input1) * 100;
        etPercen.setText(Double.toString(output));
    }
Jedi Fighter
  • 377
  • 1
  • 4
  • 20
AndroidEx
  • 15,524
  • 9
  • 54
  • 50
  • etPercen.setText(output); gives an error saying " the method setText(CharSequence) in the type TextView is not applicable for the arguments (double)" . I changed it to ("" + output) and it can be run, i think putting (""+output) makes NaN(EDIT: its like NaN plus zero), Do you know some alternative ? for setText – Jedi Fighter Apr 16 '15 at 06:15
  • i am missing some point on the if(input3 >input1). it should setText for etPercen to 100 and setText to the result equals to the 1st edittext. This reminds me of that, thx – Jedi Fighter Apr 16 '15 at 06:17
  • just want to know, that if statement have return; what does return do there?(i am not really familiar with java) – Jedi Fighter Apr 16 '15 at 06:52
  • @Jedi I put it to stop method execution after that point because we already have the answer inside the if statement and don't need to proceed further. Please tell me if something is unclear in my explanations, I can elaborate when I get to computer a little later. – AndroidEx Apr 16 '15 at 07:00
  • i found out the NaN could also be handled by my custom edittext, i changed the etPercen from EditText to my custom edittext. And NaN now gone, the result will be empty instead. If you re curious about the custom edittext check out this link [link](http://stackoverflow.com/questions/29647179/android-custom-edittextcurrency-format/29667959#29667959). Can i have more if statement(s) in there? if yes how to do that. This method is really good, efficient – Jedi Fighter Apr 16 '15 at 07:37
  • @JediFighter I feel like a custom EditText may be an overkill in this situation but if it helps... What do you mean by more if statements, in which place? And `setText(""+number)` shouldn't give any errors, it automatically converts the number to the string representation right away and concatenates the two parts. – AndroidEx Apr 16 '15 at 13:59
  • the 'if (input3 > input1){ etPercen.setText(100); return; }' there is a return there(i still not understand a return in a void in a if statement), if i want to have more conditions, can i put else if(s) and will that else if also need a return?....... and 'setText(""+number)' you re right about that – Jedi Fighter Apr 17 '15 at 00:08
  • 1
    @JediFighter ok, let's say there's no `return` inside the if statement. In this case the lines after the block are going to be executed as well, no matter what. These lines include for instance `etPercen.setText()`, but we have already put the final answer to it inside the `if`! Let `input1 = 0` and `input3 = 20`, it satisfies the `if` condition and `etPercen` gets the answer 100. If there's no `return`, the execution continues further to `double output = (input3 / input1) * 100;` - division by zero, method throws arithmetic exception and the app shuts down. Not the case with the `return` :) – AndroidEx Apr 17 '15 at 00:22
  • i see, but how about having more condition, could that happen? – Jedi Fighter Apr 17 '15 at 01:07
  • @JediFighter yep, sure. If your next condition is an alternative to the first one, just add one more `if` block after the first one. And if this new statement also gives you the answer (puts it into the edittext) and does not expect the method to continue after, then just add the `return` keyword at the end of this `if` block as well. Please tell me if you were asking about something different. – AndroidEx Apr 17 '15 at 01:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75446/discussion-between-jedi-fighter-and-android777). – Jedi Fighter Apr 17 '15 at 01:17
1

The NaN error is just Not-a-Number. I think you need to change your condition

From

 if (text1.length() != 0 )

To

if (text1.length() > 0 )

If length is -1 or 1 your if condition will still be satisfied. By using the operator > instead of != you will be assured that text1 is not empty.

Christian Abella
  • 5,747
  • 2
  • 30
  • 42
1

You are getting NaN because "" and " " are not a number Instead of using

if (text1.length() != 0 )

use

if(!TextUtils.isEmpty(text1.toString().trim()))

This is an android String utility to perform null and empty check on any String. Also you probably should to mention in your layout xml that your inputType is number

ichthyocentaurs
  • 2,173
  • 21
  • 35