One if works the next does not?

The first if statement works but once the value is set too true the second if statement should trigger but it does not see code below:

public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    TextView Serial = (TextView) findViewById((R.id.LastSerialScanned));
    TextView Location = (TextView) findViewById((R.id.LastLocationScanned));
    if(hasSerial == false)// does trigger
    {
        if(Scan.getText().length() == 8)
        {
            Serial.setText(Scan.getText());
            hasSerial = true;
            Location.setText("");
            Scan.setText("");
        }
    }
    if(hasSerial == true)// does not trigger
    {
        Location.setText(Scan.getText());
        hasSerial = false;
    }
}

Any idea why? I am sure it is obvious but this is my first time working with android studio so I am just missing something. It also did not trigger when I had a simple else statement there


Solution 1:

When the first block

if(hasSerial == false)// does trigger
{
    if(Scan.getText().length() == 8)
    {
        Serial.setText(Scan.getText());
        hasSerial = true;
        Location.setText("");
        Scan.setText("");
    }
}

triggers it changes hasSerial to true and changes Location and Scan to empty strings.

Because hasSerial is now true, this following block:

if(hasSerial == true)// does not trigger
{
    Location.setText(Scan.getText());
    hasSerial = false;
}

is also executed (in the same call to onTextChanged()) and sets hasSerial back to false.

The other line in this block has no effect, since both Scan and Location have been set to empty strings just before.

What you probably intended to do was something like:

public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    TextView Serial = (TextView) findViewById((R.id.LastSerialScanned));
    TextView Location = (TextView) findViewById((R.id.LastLocationScanned));
    if (!hasSerial) {  // does trigger
        if (Scan.getText().length() == 8)             {
            Serial.setText(Scan.getText());
            hasSerial = true;
            Location.setText("");
            Scan.setText("");
        }
    } else {
        Location.setText(Scan.getText());
        hasSerial = false;
    }
}