sandboxj
sandboxj

Reputation: 1254

Java: check if datepicker has value error

I have a

DatePicker date = new DatePicker();
date.setValue(LocalDate.now());

The field is still manually editable, so you can just remove the initial set value.

I have a button with which I want to check if the DatePicker value is empty. But when I do if(date.getValue().equals(null), I get a java.lang.NullPointerException:

Button btn = new Button();
btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent evt) {
         if(date.getValue().equals(null) {
            // do something
         }
     }
   });

How can I properly check if the value is empty?

Upvotes: 4

Views: 8080

Answers (3)

Andrew
Andrew

Reputation: 49606

if (date.getValue().equals(null) { ... }

If the value is really a null, you'll get a NullPointerException exception. So, you'd better write like:

if (date.getValue() == null) { ... }

Keep in mind, if you use equals, you should be sure that the left part of an expression (an instance this method is called on) never presents a null (like constants, String literals, enums do).


Also, you are free to replace an anonymous class with a lambda for conciseness:

btn.setOnAction(event -> { ... });

Furthermore, there's a good one-line way to set a default value if the current is a null (to LocalDate.now(), for example):

datePicker.setValue(Optional.ofNullable(datePicker.getValue()).orElse(LocalDate.now()));

Upvotes: 3

Mureinik
Mureinik

Reputation: 311326

You can't call methods on a null reference. As you've seen, that would produce a NullPointerException. Instead, you should use the == operator to check that the reference is [not] null:

if (date.getValue() == null) {
    // Here --------^

Upvotes: 2

James_D
James_D

Reputation: 209359

Check for null with

if (datePicker.getValue() == null) {
    //...
}

Upvotes: 1

Related Questions