How to handle LWUIT dialogs shown on background threads - java-me

I have written an application in LWUIT targeted for a J2ME phone (Sprint DuraXT). The application is for pickup and delivery van drivers. It receives dispatches from a back-end dispatching system that describe pickups and delivers the driver must make. As the drivers, execute the pickups and deliveries, the driver enters status information that is sent back to the dispatching system.
Now, during the processing of a pickup or delivery, the driver may be presented with error dialogs (incorrect field entry), yes/no confirmation dialogs (confirming some action) and information dialogs (indicating some status the driver should be aware of).
In addition, there is a background thread listening for dispatches coming from the back-end server. In the current implementation, this background thread can also create yes/no confirmation dialogs and information dialogs. These dialogs are more like an alert as they have an associated sound, but they are simply dialogs.
As long as these two dialogs do not occur “simultaneously” every thing works as expected. You can dismiss the dialogs and the app proceeds as expected.
However, when you are on a screen and there is a dialog already showing and a second one from the background thread occurs, you sometime wind up with the wrong screen showing and it is “frozen”. E.g. the soft keys have no effect.
My hypothesis is that there is a race condition between the threads that are dismissing the dialogs. It goes like this. The EDT is blocked showing the dialog that arises as part of the form’s logic. The background thread is also blocked showing a dialog. Now when the dialog showing on the EDT is dismissed, the form is restored, but the EDT may go off and display another form (via show()). When the dialog displayed by the background thread is dismissed, the form which was showing when the dialog was initially displayed is sometimes restored. Now, the display shows a different form than the one the EDT might have shown.
It is pretty clear that this problem is caused by the dialogs resulting from the activities of the background thread. So the basic question is: “How to handle the dialogs arising from the background thread?” I have some thoughts but none yield a particularly clean implementation. I am hoping somebody has had to deal with this same problem and has a suggestion.
I have tried synchronizing the dialog construction and display so that only one dialog can get displayed at a time. This certainly improves the UI, but does not fully resolve the problem. The race begins when the first dialog is dismissed. Here are some other ideas,
If a dialog is shown by a thread other than the EDT, call show on the form at the top of the display stack when the dialog is dismissed. This is a bit of a hack, but may be a workaround.
Run dialogs to be shown by the background thread on the EDT. There are several ways to do this, but the question is will it resolve the problem? Will using an EventDispatcher help? I have experimented using an EventDispatcher to fire an ActionEvent containing a subclass of a Dialog as a source. The subclass contains a show() method which invokes the correct form of the Dialog show method. The class holding the EventDispatcher (global to the application) listens for these events. When the event arrives, the show method is invoked. For information dialogs that simply continue execution from wherever they are dismissed, this should work. For yes/no dialogs, you may have to create something like yes/no callbacks to handle the bifurcation in the logic. And what is not obvious is if this will actually serialize the processing of the dialogs on the EDT thread. This seems complicated.
Any ideas?

I actually hit upon the solution after a bit of experimentation. Because the Dialogs are part of a more compilcated action involving yes/no Dialogs and database queries, I found I had to wrap the whole action in a class which implements the Runnable interface. Then I run the action via Display.getInstance().callSeriallyAndWait(runnable).
So others may benefit from this discussion, here is a example of one of these classes with the action embedded in the run method.
private class CancelOrder implements Runnable {
private KWMap order;
public CancelOrder(KWMap order) {
this.order = order;
}
public void run() {
String orderNum = getString(order, OrderTable.ORDER_NUM);
if (legStatusTable.isOrderStarted(orderNum)
&& !orderTable.isOrderComplete(order)) {
String msg = "You received a cancellation message for Order "
+ orderNum
+ " which has been started but is not finished."
+ "\nDo you want to keep it?";
if (app.yesNoDialog(msg, "Yes", "no")) {
sendCancelResponse(order, "Yes", "");
} else {
deleteOrder(orderNum);
sendCancelResponse(order, "No", "");
}
} else {
// order has neither been started nor completed.
deleteOrder(orderNum);
sendCancelResponse(order, "Yes", "");
app.alertDialog("Dispatcher cancelled Order " + orderNum);
}
}
}
The key thing here is that the action contains logic depending on how a user responds to a yes/no Dialog and there are operations on an underlying database and messaging subsystem as well. Except for the Dialogs, nothing in this action blocks the EDT for more than a few 100s of milliseconds, so the application runs very smoothly. The app coorectly handles dislogs stacking on top of each other which was a problem with the simple apporach of letting these actions run on the background (non EDT) thread.

Related

Is there an easy way to get the currently active dialog on the stack?

My bot is based on core-bot sample and has an interrupt function which can be invoked by certain intents during dialogs. If I'm in a dialog, and then the interrupt starts a dialog, they are both invoked via dc.beginDialog and there are on a single level in the dialog stack. For example, it would look like this
[ { id: 'viewOrderDialog', state: { dialogs: [Object] } },
{ id: 'interruptDialog', state: { dialogs: [Object] } } ]
So I can somewhat easily get the active dialog by getting the ID of the last element in the array. However, in my process I can start additional dialogs from, in this case, interruptDialog. Those are started from within a waterfall via step.beginDialog. In that case, they are no longer at the same level as the other dialogs (started from dc instead of step). I have to get into state.dialogs.dialogStack to find the id, which then can become nested again if that dialog calls another. Here is an example of what dc.activeDialog can end up looking like:
{"id":"interruptDialog","state":{"dialogs":{"dialogStack":[{"id":"waterfallDialog","state":{"options":"expediteOrder","values":{"instanceId":"d61d748e-af45-cea0-9188-63904de21dfc"},"stepIndex":0}},{"id":"escalationDialog","state":{"dialogs":{"dialogStack":[{"id":"waterfallDialog","state":{"options":{},"values":{"instanceId":"6e755278-d636-dd76-3b47-eb43e3eda1c7"},"stepIndex":2}},{"id":"emailDialog","state":{"dialogs":{"dialogStack":[{"id":"waterfallDialog","state":{"options":{},"values":{"instanceId":"87f08019-ff59-ce03-ccab-7914fb0b553b"},"stepIndex":1}},{"id":"emailPrompt","state":{"options":{"prompt":"Which email address do you want us to reply to?"},"state":{}}}]}}}]}}}]}}}
I could get down to the lowest level, which in this case is emailPrompt, but it seems it would take an inordinate amount of overhead to check and see if each level of dialogs/dialogStack was an array. (And yes, I should probably name my waterfall dialogs something other than waterfallDialog). I was hoping there would be an easy way to just get the most recent dialog off the stack, but I couldn't find anything to give me that information.
In a less general sense, I'm specifically trying to add a condition to the interrupt to prevent it from being invoked within certain dialogs. I have a step where user can write an email body, and if they write something about expediting an order, the interrupt is activating. In this specific case I decided to solve it by converting dc.activeDialog to a string and then checking to see if it includes 'emailDialog'. Then I add a condition for !activeDialog.includes('emailDialog'). Works fine for this case, but I asked the more general question because this may not be a good solution in other cases where I need to know which dialog I am in.
I can provide code snippets if needed, but the code itself isn't really important. I'm just trying to determine the best way to get the id of the currently active dialog from the dialog context.
The reason you're seeing nested dialog stacks is because you're using component dialogs.
If your interruptions are always performed on the root dialog context and that's where your interrupt dialogs get added, then there should be no need to dig into the nested dialog stacks. Because the interrupt dialog will always be in the root dialog stack you can just check your root dialog context to see if the active dialog is an interrupt dialog.
I don't know of any builtin way to determine the innermost active dialog, but if that's really what you want to do then it shouldn't be hard to create a recursive function to do it:
getInnermostActiveDialog(dc) {
var child = dc.child;
return child ? this.getInnermostActiveDialog(child) : dc.activeDialog;
}
It should be noted that the Core Bot sample makes only specific dialogs interruptible by having them extend a common base dialog class and then handling interruptions from within the dialog instead of from the bot class. You might want to follow that example by having dialogs "opt in" to interruptibility rather than having the interrupt dialog "opt out."

Is it possible to Derive class from CWinThread Class in dialog based application

I am working with Dialog based application.
My Question is that, I want to show Waiting dialog, until some database operation carried out.
i Used Derived class from CWinThread, but problem is that, when this thread close, the background (Main application dialog) remains at deactivated means( it hide behind another window).
i am thinking that, this is happening because of WaitDialog used CWinThread class.
The problem is not unique to a dialog based application. Creating windows of any kind in more than one thread is difficult and not recommended. In your case it sounds like your wait dialog is modal, while its parent dialog is in another thread. That is even worse and can lead to deadlocks between threads.
The reliable solution is to put the wait dialog (and all other GUI) in the main thread, and the lengthy database processing in a secondary thread.
Another alternative would be to use a Modeless Dialogbox which can also optionally show the status and call the DestroyWindow function when the database operation is completed -- you may need to disable some operations of the main window while the Modeless Dialogbox is visible, though.
From the comments on my previous answer, it looks like that alternative is not viable in this situation.
Maybe a better way would be to create a normal modal "wait" dialog box, start the background thread in the dialog's InitDialog, periodically check the status of the thread using a timer and end the dialog when the thread completes?

GXT custom event handler code executes multiple times

I have implemented MVP pattern in my GXT project. The system registers customers as part of it function. Also the system user can search for the registered user providing the id.
i have added an OnClick event to the "search customer" button.
/* On click search button */
view.getBtnSearch().addListener(Events.OnClick, new Listener<BaseEvent>() {
#Override
public void handleEvent(BaseEvent be) {
eventBus.fireEvent(new CustomerRegistrationTabSelectionEvent(0, false));
eventBus.fireEvent(new CustomerFetchEvent(view.getValueCustSearchParameter(), view.getValueCustSearchValue(), true));
}
});
The CustomerRegistrationTabSelectionEvent does select the relevant tab and enables other tabs. Thats all it does.
Here is the handler for the custom event CustomerFetchEvent.
eventBus.addHandler(CustomerFetchEvent.TYPE, new CustomerFetchEventHandler() {
#Override
public void fetchCustomer(CustomerFetchEvent event) {
searchCustomer(event.getParameter(), event.getParameterValue(), event.isOpenFirstTab());
}
});
The issue is the search customer method is executed multiple times and if there is a invalid search the error message dialog shows multiple popups. Within the searchCustomer method i call for service which fetch me the customer data or show the popup error message if the search is invalid.
im using GXT 2.2.5 and JRE 1.6.
Could anyone help me in finding out why the code is executed multiple times?
Added Later:
When i run the application first time the code is only executed only once, therefore only 1 popup. Then i logout of the system and log in again (navigating to the same page where the "search customer" button exists.) and the code is executed twice. Likewise equal to the number of times i create/navigate to the particular page, the code executes. Is it actually adding the event handler code without removing the last one every time i recreate the page?
Yes, it seems that 'addHandler' adds handler multiple times, but stores previous context. Your code should add handlers only once, on initialization phase. You can check the number of handlers with 'getHandlerCount' method.
Ya. I fixed it!Here is the solution Unbinding presenters necessary in GWT
U can read more here. http://draconianoverlord.com/2010/11/23/gwt-handlers.html
what happened actually was, the presenter objects where i have registered with HandlerManager to receive events were not garbage collected. Because though i remove the reference to the presenters still the HandlerManager holds a reference to those objects. So every time i kept on creating new presenters on top of the old presenters of the same class. so a event is listened by multiple objects of the same class. so u need to ensure that the unused presenters are garbage collected by removing the registered handlers
in HandlerManager.

minimize and getting back the display

I want to minimize my app and after the timer end get it back.
I use code below.
To minimize application use following line of code:
Display.getDisplay (MIDLET_CLASS_NAME).setCurrent (null);
To get the screen back use the following:
Display.getDisplay (MIDLET_CLASS_NAME).setCurrent (myCanvas);
But when phone display is dismissed and going to clock mode my midlet display isn't shown until press any button.
any idea?
From your question it sounds that you expect setCurrent to somehow "force" device to immediately display your screen or maybe return only after screen gets visible.
This is not so, as clearly explained in the API documentation for Display.setCurrent:
Requests that a different Displayable object be made visible on the display. The change will typically not take effect immediately. It may be delayed so that it occurs between event delivery method calls, although it is not guaranteed to occur before the next event delivery method is called. The setCurrent method returns immediately, without waiting for the change to take place...
...if the application is in the background, passing a non-null reference to setCurrent may be interpreted by the application management software as a request that the application is requesting to be brought to the foreground... These are only requests, and there is no requirement that the application management software comply with these requests in a timely fashion if at all...
Consider redesigning your MIDlet to adjust to specified behavior.
If myCanvas is an instance of Canvas, one can use showNotify() events.
For a generic Displayable screen isShown() method checks if the it is actually visible on the display.
Sometimes it could even make sense to let user explicitly confirm return from background, like
display.setCurrent(new Alert("back to foreground", "dismiss to continue...",
null, AlertType.INFO), myCanvas);

Saving the states of JavaFX controls on exit

I have a bunch of control objects (TextBoxes, to be precise) that get injected into my code using the #FXML annotation during the FXML load.
I would like to save the states of these controls, specifically the text values, when the user closes the Scene by clicking the close box on the title bar.
However, when I trap the CloseRequest event in an OnCloseRequest handler I find that the values of the control variables are null (the original injection works, so this is something that happens in between the loading of the FXML and the calling of OnCloseRequest).
Can anyone explain this behavior and/or suggest how I can get the functionality that I want?
TIA
onCloseRequest is
Called when there is an external request to close this Window. ...
(from Javadoc). One of the meanings of "external request" is when you close the window through OS native window close button. The closeRequest event is not triggered through the programmatic stage.close() or stage.hide() calls. So consider to handle onHiding or onHidden events.
Otherwise post your OnCloseRequest handler code.

Resources