Test if a datepicker has a value


Question

I have a two datapickers, d1 and d2. There is a filter function that should filter by d1 only, d2 only or both d1 and d2.

@FXML
DatePicker d1;
@FXML
DatePicker d2;

public void filter(){
  SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

  String st = ft.format(ft.parse(this.d1.getValue().toString())));
  String en = ft.format(ft.parse(this.d2.getValue().toString())));

  if(st == null && en != null)
    filterbySt(d1);
  else
    filterbyEn(d2);
}

If d1 or d2 are not set, I get a null pointer exception

How do I test if a datepicker has not been set ?

1
0
9/21/2014 10:12:53 PM

Problem

If d1/d2 ae not set, d1.getValue() returns null and using d1.getValue().toString() will throw NullPointerException.

Solution

Just put a null check before you try to get the value out of the datepicker. If datePicker.getValue() is null, it implies datepicker has not been set

...
String st, en =null;
if(d1.getValue() != null){
  st = ft.format(ft.parse(this.d1.getValue().toString())));
}
if(d2.getValue() != null){
  en = ft.format(ft.parse(this.d2.getValue().toString())));
}
...
2
9/21/2014 10:09:27 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon