ChangeHandler not recognising a blank date - java

I am checking for a change in value of a date. The ValueChangeHandler is recognising a date (e.g. 1/5/2014 is updated to the DB when entered). However, when I delete a date it is not recognised (i.e., the DB is not updated to null - I have tried Backspace, highlight and Del, overtyping with spaces). I then entered a new date (2/5/2014) and this was updated to the DB. Any ideas as to why this code does not recognise that I have removed the date please.
Regards,
Glyn
I have updated this with the code suggested by Braj. Unfortunately this did not work.
final DateBox awardedDate = new DateBox();
awardedDate.setFormat(new DefaultFormat(DateTimeFormat.getFormat("dd/MM/yyyy")));
awardedDate.setValue(ymAwards.getCaAwardedDate());
awardedDate.setWidth("75px");
//Add change handler for the awarded date.
//Only a Leader or Administrator can update the date
if (accountLevel.equals("Leader") || accountLevel.equals("Administrator")) {
awardedDate.addValueChangeHandler(new ValueChangeHandler<java.util.Date>() {
int pog = 0;
public void onValueChange(ValueChangeEvent<java.util.Date> event) {
if (pog == 0) {
pog++;
Window.alert("First change hadler.");
//Check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateAwarded = awardedDate.getValue() == null ? null : new java.sql.Date(awardedDate.getValue().getTime());
AsyncCallback<YMAwards> callback = new YMAwardedDateHandler<YMAwards>();
rpc.updateYMAwarded(youthMemberID, returnAwID, sqlDateAwarded, callback);
}else{
pog = 0;
}
}
});
awardedDate.getTextBox().addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (event.getValue() == null) {
Window.alert("Second change hadler.");
//Check for a null date and handle it for dateBoxArchived and dateBoxPackOut
java.sql.Date sqlDateAwarded = awardedDate.getValue() == null ? null : new java.sql.Date(awardedDate.getValue().getTime());
AsyncCallback<YMAwards> callback = new YMAwardedDateHandler<YMAwards>();
rpc.updateYMAwarded(youthMemberID, returnAwID, sqlDateAwarded, callback);
}
}
});
}

Add this line:
awardDate.setFireNullValues(true);
This was added in GWT 2.5.

Try this one also
final DateBox dateBox = new DateBox();
dateBox.getTextBox().addValueChangeHandler(new ValueChangeHandler<String>() {
#Override
public void onValueChange(ValueChangeEvent<String> event) {
if (dateBox.getValue() == null) {
System.out.println("date value is empty");
// your code here
}
}
});
output:
date value is empty
DateBox#addValueChangeHandler() fires when there is any change in date via date picker.
You can check the value in text box using TextBox#addValueChangeHandler().

Related

React Scheduler data update issue

I am having a real deal that I can't get over with. I am using ScheduleComponent in ReactJS to create a calendar and some appointments.
Here is my component which uses a ScheduleComponent. I have no idea how can I update some data from my API.
const CalendarComponent = () => {
const [schedules, setSchedules] = useState([]);
const dataManager = new DataManager({
url: `http://localhost:8080/schedule/calendar`,
crudUrl: `http://localhost:8080/schedule/updateCalendar`,
adaptor: new ODataV4Adaptor,
crossDomain: true
});
return(
<section className="adminSection">
<ScheduleComponent width='100%' currentView='Month' eventSettings={{dataSource: dataManager}}>
<ViewsDirective>
<ViewDirective option='Day'/>
<ViewDirective option='Week'/>
<ViewDirective option='Month'/>
<ViewDirective option='Agenda'/>
<ViewDirective option='MonthAgenda'/>
<ViewDirective option='TimelineDay'/>
<ViewDirective option='TimelineMonth'/>
</ViewsDirective>
<Inject services={[Day, Week, WorkWeek, Month, Agenda, MonthAgenda, TimelineViews, TimelineMonth]} />
</ScheduleComponent>
</section>
);
};
export default CalendarComponent;
And there is my Java ScheduleResponse for getting apropriate data from database.
public record ScheduleResponse(
#JsonProperty("StartTime") LocalDateTime startTime,
#JsonProperty("EndTime") LocalDateTime endTime,
#JsonProperty("Subject") String subject
) {
public static ScheduleResponse fromSchedule(Schedule schedule){
return new ScheduleResponse(
schedule.getDateTimeFrom(),
schedule.getDateTimeTo(),
schedule.getSubject());
}
}
I would like to know how can I refer to a single data from dataSource using this component, and I have no clue.
We suggest you use addParams of Query to handle the filtering in server and for the same we have prepared a sample below.
Service: https://www.syncfusion.com/downloads/support/directtrac/general/ze/Service-294388409
Sample: https://stackblitz.com/edit/add-param-front-end?file=index.js
In the above sample based on Subject field we have filtered the data from back end.
UG Link: https://ej2.syncfusion.com/react/documentation/schedule/data-binding/#passing-additional-parameters-to-the-server
Client side code
public onCheckBoxChange(): void {
let predicate: any;
const checkBoxes: CheckBox[] = [this.confirmObj];
checkBoxes.forEach((checkBoxObj: CheckBox) => {
if (checkBoxObj.checked) {
predicate = predicate ? predicate + ',' + checkBoxObj.label : checkBoxObj.label;
}
});
this.scheduleObj.eventSettings.query = new Query().addParams(
'Subject',
predicate ? predicate : ''
);
}
Server side code:
public JsonResult LoadData(Params param) // Here we get the Start and End Date and based on that can filter the data and return to Scheduler
{
DateTime start = param.StartDate;
DateTime end = param.EndDate;
var subject = param.Subject;
var data = db.ScheduleEventDatas.Where(app => (app.StartTime >= start && app.StartTime <= end) || (app.RecurrenceRule != null && app.RecurrenceRule != "")).ToList(); // Here filtering the events based on the start and end date value.
if (param.Subject != null)
{
// Filter data based on additional parameter
data = db.ScheduleEventDatas.Where(app => (app.StartTime >= start && app.StartTime <= end && app.Subject == subject) || (app.RecurrenceRule != null && app.RecurrenceRule != "")).ToList();
}
return Json(data, JsonRequestBehavior.AllowGet);
}
public class Params
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Subject { get; set; }
}

Android: NullPointerException 'double java.lang.Double.doubleValue()'

I'm new to android programming and I'm having a problem with my codes. Can anyone help me or point out the cause of my error because I'm not really sure why it's giving me a NullPointerException when its a text view or if that is possible.
LogCat:
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
at com.example.app.rosbridge.MainActivity$2$1.run(MainActivity.java:133)
Here is the code for that line:
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
But when i run my app my voltage is setting null and here is the code for the voltage:
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
Here is the full code:
public class MainActivity extends Activity {
private TextView voltage, current, percentage, status;
private SubscribedData<BatteryState> batteryStateData;
private RosbridgeListener rosbridge;
private boolean subscribed = false;
private boolean advertised = false;
/** Indicates that Lint should ignore the specified warnings for the annotated element. */
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
Button settings_btn = (Button) findViewById(R.id.connect_btn);
voltage = findViewById(R.id.voltage_txt);
current = findViewById(R.id.current_txt);
percentage = findViewById(R.id.percentage_txt);
status = findViewById(R.id.status_txt);
connectButton = findViewById(R.id.connect_btn);
batteryStateData = new SubscribedData<>();
final Type batteryStateType = new TypeToken<SubscribedData<BatteryState>>() {
}.getType();
// ROSBRIDGE protocol allows access to underlying ROS messages and services as serialized JavaScript Object Notation (JSON) objects
WebSocket protocol communicates to a server for the connection from a user's web browser
//A connection to the rosbridge thru the IP address of the robot from the socket
rosbridge = new RosbridgeListener("ws://10.24.204.231:9090");
rosbridge.setOnDataReceivedListener(new RosbridgeMessageListener() {
// a running thread that when the connection is made the data of the topic will serialize and deserialized java objects to (and from) JSON. #param msg
#Override
public void onDataReceived(final String msg) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
batteryStateData = new Gson().fromJson(msg, batteryStateType);
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
percentage.setText(String.format("%.2f%s", batteryStateData.msg.percentage, "%"));
status.setText(String.format("%s", PowerSupplyStatus.values()[batteryStateData.msg.powerSupplyStatus]));
}
});
Log.d("B9T", String.format("Received data: %s", msg));
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!subscribed) {
rosbridge.Subscribe("/battery", "sensor_msgs/BatteryState");
subscribed = true;
connectButton.setText("Disconnect");
} else {
rosbridge.UnSubscribe("/battery");
subscribed = false;
connectButton.setText("Connect");
}
}
});
Everytime when you are setting the text to textview, you must need to check if it is not null.
You can check null before you set text on textview like the following.
#Override
public void run() {
batteryStateData = new Gson().fromJson(msg, batteryStateType);
// check null before set text or calculate something
if(batteryStateData.msg.current != null){
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
}
// you can check belows like above
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
percentage.setText(String.format("%.2f%s", batteryStateData.msg.percentage, "%"));
status.setText(String.format("%s", PowerSupplyStatus.values()[batteryStateData.msg.powerSupplyStatus]));
}
Check weather your created class with GSON is not null
and then check class fields values is not null or 0.
batteryStateData = new Gson().fromJson(msg, batteryStateType);
if (batteryStateData != null) {
if (batteryStateData.msg.voltage!=0)
voltage.setText(String.format("%.4f%s", batteryStateData.msg.voltage, "v"));
if (batteryStateData.msg.current!=0)
current.setText(String.format("%.4f%s", batteryStateData.msg.current * Math.pow(10, 6), "A"));
if (batteryStateData.msg.percentage!=0)
percentage.setText(String.format("%.2f%s", batteryStateData.msg.percentage, "%"));
if (batteryStateData.msg.values !=null)
status.setText(String.format("%s", PowerSupplyStatus.values()[batteryStateData.msg.powerSupplyStatus]));
}

GWT DateBox - Disable specific date

I want to disable a specific date in my date box. I tried it with this code, but the specified date (current day) does not get disabled.
final DateBox dateBox = new DateBox();
dateBox.getDatePicker().addShowRangeHandler(new ShowRangeHandler<Date>() {
#Override
public void onShowRange(final ShowRangeEvent<Date> event) {
List<Date> disabledDates = new ArrayList<Date>();
disabledDates.add(new Date());
dateBox.getDatePicker().setTransientEnabledOnDates(false, disabledDates);
}
});
Is there an other way to do this?
Edit: Following the example of apanizo, the day 29.5 looks greyed out, but is clickable nevertheless.
Really sorry, I did not test the code of my last answer.
I have just tried and your code worked to me, the only thing that I did was pass all the dates that I do not want through the setTransientEnabledOnDates(false, dateToDisable); method.
Example:
public void onModuleLoad() {
final DateBox dateBox = new DateBox();
dateBox.getDatePicker().addShowRangeHandler(new ShowRangeHandler<Date>() {
#Override
public void onShowRange(final ShowRangeEvent<Date> dateShowRangeEvent) {
final Date today = new Date(); //30 May 3014
final Date yesterday = new Date(today.getTime()- 24*60*60*1000);
//disabling yesterday - 29 May of 2014
dateBox.getDatePicker().setTransientEnabledOnDates(false, yesterday);
}
});
RootPanel.get().add(dateBox);
}
If you want to disable the click event on a disabled date, this is a resolved and not delivered bug.
See:
https://code.google.com/p/google-web-toolkit/issues/detail?id=7876
I think in the GWT's 2.7 version it will be released, in the mean time you can patch it introducing in the line 77 of com.google.gwt.user.datepicker.client.CellGridImpl :
addDomHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
if (isActive(Cell.this)) {
setSelected(Cell.this);
}
}
}, ClickEvent.getType());
In detail here
Simply add a value changed listener on date picker to listen for any change in the date.
For example if current date is not allowed and it's selected then simply discard the changes and revert back to previous date or show a warning message as well if needed and add style for current date to look it as disabled.
Here date time format is used to check for date only, time is discarded while checking dates.
Sample code:
private Date prevDate;
...
final DateBox dateBox = new DateBox();
final DateTimeFormat dateTimeFormat=DateTimeFormat.getFormat("MM/dd/yyyy");
dateBox.getDatePicker().addValueChangeHandler(new ValueChangeHandler<Date>() {
#Override
public void onValueChange(ValueChangeEvent<Date> event) {
if (dateTimeFormat.format(event.getValue()).equals(dateTimeFormat.format(new Date()))) {
dateBox.setValue(prevDate);
// show warning message here
}else{
prevDate=event.getValue();
}
}
});

How to setText() into not enabled JFormattedTextField

I've got problem trying to setText into my JFormattedTextField when it is not enabled. It's all right, when it is... String value is not empty, but the field stays empty.
private SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy") {
#Override
public Date parse(String source) throws ParseException {
return (source != null && !source.trim().equals("") && !source.trim().equals(". .")) ? super.parse(source) : null;
}
};
...
jFormattedTextField1 = new javax.swing.JFormattedTextField();
`enter code here`...
jFormattedTextField1.setFormatterFactory(new DefaultFormatterFactory(mf));
jFormattedTextField2.setFormatterFactory(new DefaultFormatterFactory(mf));
jFormattedTextField1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
showPopup(jFormattedTextField1);
}
});
`jFormattedTextField1.setText("22.10.2012");`
just use Apache StringUtils.isBlank or StringUtils.isNotblank quite handy instead checking for null or empty.
The prolem was with Look and Feel Nimbus. The colour of text and TextField is the same

How to disable CustomValidator for a specific scenario

I have a form which uses CustomValidator to check for non empty field whenever we try to Add a record (PARAMETER, VALUE)
I'm looking for a way to disable form validation when I'm trying to Delete (the user can delete an empty listGridRecord if he changes his mind and needs no more to add).
I'm using this custom validator:
CustomValidator validatorParameter = new CustomValidator() {
#Override
protected boolean condition(Object value) {
parameterName = (String) value;
if ((value == null || ((String) value).trim().isEmpty())) {
rowIsValidate = false;
return false;
} else {
rowIsValidate = true;
return true;
}
}
};
which I'm setting in an init() method this way:
parametersListGrid.getField(PARAMETER).setValidators(validatorParameter);
I tried setting a flag "noValidation" on true whenever I detect a click on Delete button and used it this way:
CustomValidator validatorParameter = new CustomValidator() {
#Override
protected boolean condition(Object value) {
parameterName = (String) value;
if (((value == null || ((String) value).trim().isEmpty())) && !noValidation){
rowIsValidate = false;
return false;
} else {
rowIsValidate = true;
return true;
}
}
};
but I figured out that this flag is set later on after the validation happened so
rowIsValidate stays false and we can't delete the empty record given the errors shown after validation;
Any idea on how to pass this validation step just in deletion scenario?
Call discardEdits(rowNum) before deleting a record.
Same question is asked on SmartClient Forums.

Categories

Resources