What code do I use to create a validation class in AndroidStudio?

1

I'm trying to create a class to check if the 2 EditText fields are filled, called Validacao . I wanted to call type:

if (Validacao(TextoA, TextoB) == true) {
    executa código;

I'm not sure how to code the class Validacao . Do I need to have a Validacao() constructor? What would the code look like?

import android.widget.EditText;
import android.widget.Toast;

public class Validacao {
    private boolean x = true;
    private boolean y = true;
    private boolean z = true;
    private boolean a = false;

    public Validacao(EditText textA, EditText textB) {
        // Valida para ter todos os 2 campos preenchidos
        if ((textA.getText().toString().isEmpty()) && (textB.getText().toString().isEmpty())) {
            z = false;
            Toast toast = Toast.makeText(this, "Informe os números." , Toast.LENGTH_SHORT);
            toast.show();
        } else if (textA.getText().toString().isEmpty()) {
            x = false;
            Toast toast = Toast.makeText(this, "Informe o primeiro número." , Toast.LENGTH_SHORT);
            toast.show();
        } else if (textB.getText().toString().isEmpty()) {
            y = false;
            Toast toast = Toast.makeText(this, "Informe o segundo número." , Toast.LENGTH_SHORT);
            toast.show();
        }
    }
    if (x && y && z)
        a = true;
    return a;
}
    
asked by anonymous 20.07.2018 / 01:35

1 answer

0

When defining a function with the same class name, this function will be the constructor function of this class, and it should be invoked through the new

As you are creating a validation class, I suggest that you use static functions and the logic to check how many variables are valid is done where these methods are called

For example:

public class Validacao {
    public Validacao() {  }

    public static boolean isValid(EditText et, String msg, Context context) {
        if (et.getText().toString().isEmpty()) {
            Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
            toast.show();

            return false;
        } else {
            return true;
        }
    }
}

To use:

if (Validacao.isValid(x, "Informe o primeiro número", getApplicationContext()) && Validacao.isValid(y, , "Informe o segundo número", getApplicationContext()) && Validacao.isValid(z, "Informe o terceiro número", getApplicationContext())) {
    // Faz alguma coisa
}

You can also create a custom function for each variable

    
20.07.2018 / 02:43