mattfred
mattfred

Reputation: 2749

Android Data Validation

I am wondering what is the most effective form of data validation for android. So, when getting a value from an EditText how should the value given be validated before it is used? I currently check to make sure the string returned from getText().toString() is not null or empty using the guava library:

Strings.isNullOrEmpty(editText.getText().toString())

Then, depending on what type of data I am expecting, I create a method to see if the data can be parsed. So if I am expecting a double I will create a method like this:

private boolean isDouble(String string) {
    try {
        double stringDouble = Double.parseDouble(string);
        return true;
    } catch (Exception e)
    {
        return false;
    }
}

Is there a simpler way to do this without the need to create a separate method for each type of data I am expecting to receive?

Upvotes: 0

Views: 113

Answers (2)

Konstantin Kiriushyn
Konstantin Kiriushyn

Reputation: 627

If you are using EditText you should know what purposes it serves. Usually you are expecting to have just a plain string to, for example, send it to server or store in SharedPreferences.

But, if you want a particular data to be filled in, you can use Pattern class for validation. In case of number values you are using android:inputType="number" and when converting it using Integer.valueOf(text)

Upvotes: 1

Fabian
Fabian

Reputation: 2713

I've used the edittext-validator the last time I needed a quick validation. Works like charm :)

https://github.com/vekexasia/android-edittext-validator

Upvotes: 1

Related Questions