Ilim Sarykbaev
Ilim Sarykbaev

Reputation: 35

Error converting from String to int to Vaadin

I'm trying to convert a String to int in Vaadin. Here is the code:

TextField name = new TextField();
int num;
num = Integer.parseInt(String.valueOf(name.getValue()));
Paragraph greeting = new Paragraph("");
Button button = new Button("Result", event -> {
    greeting.setText(" " + num * 500);
});
add(name, button, greeting);

And here is the error:

There was an exception while trying to navigate to '' with the exception message 'Error creating bean with name 'com.gmail.ilim.MainView': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.gmail.ilim.MainView]: Constructor threw exception; nested exception is java.lang.NumberFormatException: For input string: ""'

Upvotes: 0

Views: 318

Answers (2)

kscherrer
kscherrer

Reputation: 5766

As it was said in the comments:

1) parse the input value only within the button's clicklistener, not directly inside the constructor of the view (at that point, the TextField will always have empty value)

2) catch the NumberFormatException. Even when having point 1 taken care of, the user can always type in non-numeric stuff which will not be parseable to Integer

TextField name = new TextField();
Paragraph greeting = new Paragraph("");
Button button = new Button("Result", event -> {
    int num;
    try {
        num = Integer.parseInt(String.valueOf(name.getValue()));
    } catch (NumberFormatException e) {
        num = 0; // your default value
        // you should also let the user know he didnt enter a valid number
        Notification.show("Please enter a valid number");
    }
    greeting.setText(" " + num * 500);
});
add(name, button, greeting);

Another possibility is to directly use a IntegerField instead of TextField. This is only available for Vaadin 14.1.x

Yet another possibility that comes into my mind is using a Binder - when binding the textField you could add a StringToIntegerConverter. This is going to be a little more complicated and I wouldn't go that route just for this.

Upvotes: 2

NikNik
NikNik

Reputation: 2301

As the other people in comments said, one solution would be to catch the Exception so:

try {
  num = Integer.parseInt(name.getValue());
} catch (NumberFormatException nfe) {
  num = 1; // your default value
}
...

Upvotes: 1

Related Questions