Verify data type of an EditText

1

Hello everyone, I have the following:

                // recojo 2 valores del EditText
                String valor1 = recullFrom.getText().toString();
                String valor2 = recullTo.getText().toString();
                // Transformarlos en int para usarlos
                int nro1 = Integer.parseInt(valor1);
                int nro2 = Integer.parseInt(valor2);

How can I do to verify that value1 and value2 are numbers ??

I need to use them for a random and clear if I put text right now I would take it and peta.

Thanks!

    
asked by Montse Mkd 26.09.2018 в 13:25
source

2 answers

1

I recommend you in the layout of the activity configures so that the data of that imput can only be numbers.

<EditText 
   android:numeric="integer"
   android:inputType="number">
</EditText>

In case you do not want to do that you can put it in a try to determine if it is numeric or not.

try {
   int nro1 = Integer.parseInt(valor1);
   Log.i("",num+" is a number");
} catch (NumberFormatException e) {
   Log.i("",nro1 +" is not a number");
}
    
answered by 26.09.2018 / 13:46
source
1

One solution would be to create a method that confirms whether it is of the integer type or not. Then I leave you in example:

    public boolean isInteger(String numero){
        boolean resultado;
        try{
            Integer.parseInt(numero);
            resultado=true;
        }catch(Exception e){resultado=false;};

        return resultado;
    }

If the method returns "true" then it is an integer type data, if it returns "false" then it is not. I hope I have helped you.

    
answered by 26.09.2018 в 13:48