how to exchange data between two Blackberry Applications? - java

To exchange data between apps I have created 2 applications, one is a UI application and the other is a background application, by setting an alternate entrypoint
I was able to find a similar question but was not able get the help I need there
I am able to create Global Events and a Global Listener,
but my problem is how to transfer Data from one application to another.
In UI APPLICATION we can post globalEvent
ApplicationManager.getApplicationManager().postGlobalEvent(0xba4b84944bb7);
In Background Application we can Listen and send the Acknowledgement
public void eventOccurred( long guid, int data0, int data1, Object object0, Object object1)
{
//Is this the GlobalEvent we are waiting for?
//Long = com.samples.globalEventFiring.GlobalEventListening
if (guid == 0x7d3a74a5ccfe6483L)
{
//Yes it is.
System.out.println("Acknowledgement received.");
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Event was fired and acknowledged.");
}
});
}
}
But how to transfer data from background application to ui application.How UI application can access data or objects of background application.

you can use Runtime storage as a central location to share your data between background and UI thread.

You can use the int and Object arguments in the event system to pass data between the application instances. When posting the event, use the postGlobalEvent overload that takes ints and Objects. And in the event handler, downcast object0 or object1 as necessary.

Related

Vaadin - how to stop waiting for server response?

I have page with grid. I am loading data through service to grid. Loading and computing all data takes about 20-40 seconds. When I press button to get data, page start loading (classical in vaadin top loading indicator start loading).
My question is, how can I stop loading/waiting for data?
I can't stop searching process on that server I am getting data from, it dont have this functionality, I can only request for data, and wait for them.
Should I stop some thread? should i use something like this.getUI... and somewhere here stop it?
I am using vaadin 7.7.4
Thank you :)
You should use threads for this.
You will need to separate your logic, that the main thread does add all components to the UI.
This thread then also needs to spawn a new thread which does fetch the data and then updates the UI accordingly.
To update the UI once the data has been fetched from the backend you will need to activate push in your UI.
Don't forget to synchronise thread access to the UI with something like:
ui.access(new Runnable() {
#Override
public void run() {
...grid_update_with_new_data... ;
}
});
The fetching of the data should occur outside the ui.access method, otherwise your UI will freeze during backend data loading.
See this post for more technical details
Using Thread with Vaadin? and https://vaadin.com/docs/v7/framework/advanced/advanced-push.html
#André Schild This is simplified code. When I hit search button, app start searching, no problem with that. Problem is how to STOP searching, before its done. Enough for me is to stop waiting for response, and stop loading bar at top of the page, but I dont know how to achive this.
#SpringComponent
#UIScope
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class DistraintSearchComponent extends CustomComponent {
#Autowired
private Service service
private Button searchButton = new Button("Search");
public void init(){
searchButton.addClickListener(new ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
List<Results> results = service.findByFilter(filter);
refreshGrid(results);
}
});
}
}

Long network operation needs to update the UI in Android many times

my Activity shows to the user some data, which are download from a web server. Data could change over the time, so the web server communicates new updates to the connected clients.
So the work of my application is basically this:
while ( true ) {
wait for updates;
update the UI;
}
This code could run forever, and during its life it should update the UI many times.
What class should I use to implement this code?
Thread or Runnable seems the easiest solutions to my problem, but how could I comunicate to the UI thread?
onServerChangesListener... refresh UI
public void serverStateWrappr(){
Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
_localstr = getStuff((String) msg.obj)
updateAdapter(_localstr)
}}
from the thread which has a handleRef ...
while (onChangesForClient) {
Message msg = Message.obtain();
msg.what=1;
msg.obj=newData;
//TODO this is the comment for UI
mhandleRef.sendMessage(msg);
}
}
You should probably go with an asyncTask, calling runOnUiThread when you need to update the UI. Have a look to this question to see how activity.runOnUiThread() should be used
IMHO AsyncTask is preferrable, because it gives you more fine-grained control over your background task via onPreExecute(), onPostExecute()

Android right approach : where JSON response should be parsed - in UI thread, or in another one?

I just wondering - where the JSONObject or JSONArray received from the web-server should be parsed in Android app - in the main UI or should be delivered to the another one ?
For example, I'm using Volley library :
private void fetchResults(){
RequestQueue queue = Volley.newRequestQueue(mContext);
String url = AuthenticationRequester.URL_GET_ALL_ORDERS;
JsonArrayRequest jsonDepartureObj = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
iVolleyCallback.onJSONArraySuccess(jsonArray);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hide the progress dialog
}
});
queue.add(jsonDepartureObj);
}
So should I put the iVolleyCallback.onJSONArraySuccess(jsonArray); in another thread execution or can be maintained the the main UI thread ?
Let's imagine that the incoming JSON is big and needs some time to be proceeded ?
The same question relates to the AsyncTask and to other possible ways working with the web-services in Android.
It is prefered that, every task that takes long time, should be proccessed in another thread to avoid overloading MainThread:
AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
So if you know that you have big data and it will take time, you will use new thread, but if the data are small and takes less time, why take the risk? Move that to the new thread too
If, as you say yourself, the JSON data could be huge, and it could take some time to process, I think you could (or should?) try to process it in an AsyncTask. By doing this your UI thread will not be frozen during the processing.
In most GUI designs (not just Android), there are several threads having different roles and responsibilities:
The "main thread," running at "normal" dispatching priority, basically has nothing else to do but to respond promptly to the demands of the user-interface system. When "messages" arrive for its consumption, this thread immediately pre-empts the other threads so that the message can be processed quickly. Like any good manager ... ;-) ... they don't do the work themselves. They pass it off to other people.
When asynchronous requests (JSON ... etc.) are involved, there's usually a small "pool" of threads who are responsible for sending those to the host, receiving the response, doing the encoding/decoding, and then either acting-on the response or passing it along. These threads spend nearly all their time waiting on the host. They operate at a slightly-inferior dispatching priority.
Worker threads, operating at an even-more inferior priority, do any work that is computationally time-consuming. As much as possible, these threads don't do much I/O. They give-up their time slices quickly and readily to any other thread, but they usually consume their entire time slice when they can get one.
Potentially long running operations should always happen on a separate thread, or really any work (within reason...) that can be done on a separate thread should.
In your case, you're using Volley, so it's very easy for you to override your Request<T>'s parseNetworkResponse(NetworkResponse response); method, and parse the response on a background thread (since this method already runs on a background thread) before it's delivered. Since it's relatively seamless to do so, there really isn't a reason to not parse the response on a background thread.
Try this https://github.com/yakivmospan/volley-request-manager
//Queue using custom listener
RequestManager.queue()
.useBackgroundQueue()
.addRequest(new TestJsonRequest(), mRequestCallback)
.start();
private RequestCallback mRequestCallback = new RequestCallback<JSONObject, ResultType>() {
#Override
public ResultType doInBackground(JSONObject response) {
//parse and save response data
return new ResultType();
}
#Override
public void onPostExecute(ResultType result) {
//update UI here
Toast.makeText(getApplicationContext(), "Toast from UI", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(VolleyError error) {
//handle errors here (UI thread)
L.e(error.toString());
}
};

JavaFX Block the UI (and the code) until a server call is finished

This topic is around in countless articles of "not blocking the JavaFX UI during a long lasting call into something time consuming (server)". I know that and I googled and tried a lot.
Most of the "Internet" explains that long lasting calls caused by JavaFX events need to be made in an extra thread. After the thread is finished, you update the FX UI with the results via Platform.runLater(). Most of the FX Libraries encapsulate this with sophisticated code constructs (really cool stuff).
My current problem with it is: We are migrating a Swing rich client to JavaFX. It is a huge one, so we have to constantly include/replace JavaFX UI into it, until it is a full FX client.
There is some functionality in the client that does a server call and has to wait before the user can continue with his work.
The server uses JEE6 with stateless session beans and interfaces. The interfaces are known to the client and with a little library of our own, we implemented a little proxy hiding away the communication layer from the client.
The client just creates a "RemoteProxy" with the library then just calling the remote interface and the library propagates the call to the server. The method is called and the result or Exception transported back to the client. For the client this appears like a local call.
Here is the problem. A typical code fragment looks like this:
...
ServerRemoteInterface myServerRemoteProxy = Helper.getProxyForInterface(ServerRemoteInterface.class) ;
...
ComplexResult result = myServerRemoteProxy.doThingsOnServer(SerializableParameter p1 ...)
doSomethingUsefull() ;
The call to the server is triggered in the Swing UI thread (by a listener). It stops the execution of the program (Listener Code) although it is done in an extra thread. "doSomethingUsefull()" is called after the server got back. The developer does not have to take care about threading here.
How is it accomplished? By using the "Spin Library" (http://spin.sourceforge.net/).
It does some clever tricks with the Swing EDT.
An alternative would be to use a modal Dialog, but we decided not not have an extra window, but have a glasspane disabling some UI components instead.
So long explanation and short question...
Is there something similar for JavaFX helping us to seamlessly call a server, stop the program execution until it got back and NOT blocking the JavaFX UI? Best would be if it can work together with Java Swing parts of code.
EDIT... Adding an very compressed example for demonstration of the use with hidden JDialog.
We need the server remote interface. Any interface will do.
public interface ServerRemoteInterface
{
public String method1() ; // String result in our case for test purposes
public String method2() ; // Exceptions would also be possible.
}
Then we need the Proxy Invocation Handler
public class ServerProxy implements InvocationHandler
{
public Object result;
JDialog modalDialog = new JDialog((Frame)null, true);
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
ServerCallHelper serverThread = new ServerCallHelper(args, method) ;
modalDialog.setLocation(4000, 5000); // as if using Spin library. Here we use the dialog to block in a location off the screen.
serverThread.start();
modalDialog.setVisible(true) ;
return result;
}
class ServerCallHelper extends Thread
{
Object[] args;
Method method;
public ServerCallHelper(Object[] args, Method method)
{
this.args = args;
this.method = method;
}
public void run()
{
// do a server call via rmi or tunnel it via http, REST or whatever and provide the call parameters. On the server side there must be a receiver propagating the call to the wanted session bean.
// here we just do a simulation
try
{
Thread.sleep(3000);
} catch (InterruptedException e)
{
// interupt is ok here.
}
// now hand the result from the call back. we simulate a fix result
// We also could have caught the Exception and deal with it.
result = "Simulated Result" ;
// Since we are in the worker thread => inform EDT To close the dialog.
SwingUtilities.invokeLater(()->modalDialog.setVisible(false));
}
}
}
And finally some code to show the functionality
public class SampleUI extends JFrame
{
JButton serverCallButton = new JButton("Call server") ;
JLabel resultLabel = new JLabel("No result so far") ;
public SampleUI()
{
JPanel cont = new JPanel() ;
cont.add(serverCallButton) ;
cont.add(resultLabel) ;
this.setContentPane(cont);
serverCallButton.addActionListener((e)->processServerButtonCall());
}
private void processServerButtonCall()
{
ServerRemoteInterface serverAccess = (ServerRemoteInterface) Proxy.newProxyInstance(SampleUI.class.getClassLoader(), new Class[]{ServerRemoteInterface.class}, new ServerProxy());
String result = serverAccess.method1() ;
resultLabel.setText(result);
}
public static void main(String[] args)
{
SampleUI sampleUI = new SampleUI() ;
sampleUI.pack();
sampleUI.setVisible(true);
}
}
The example is very compressed but should show the principle. As a developer I do not have to take care that the call to the server is really a server call. To me it's like a local call. I do not even have to take care that I am in the EDT Thread, because i just am.
As I said it would work the same way in FX with a modal stage. I tried to set it to opaque 0.0 => It is not drawn anyway. This works.
The question remains: Are there ways to get around the extra JDialog or Stage ?
If I understood your intentions correctly, this is a use case for Future:
CompletableFuture.supplyAsync(() -> myServerRemoteProxy.doThingsOnServer(...))
.thenAccept(result -> doSomethingUseful(result));
Both the server call and doSomethingUseful will be executed in another thread, so you need to use Platform.runLater in doSomethingUseful if you want to access the scene graph.
Like Tomas said the solution is a nested Event Loop.
Currectly Java FX already has such an implementation:
com.sun.javafx.tk.Toolkit.getToolkit()
provides the methods enterNestedEventLoop and exitNestedEventLoop.
From the package name you can tell that it is sun(oracle) specific and should not be used. I read that people already asked Oracle to move it it "Platform" because it is a very useful feature.
Maybe we use it anyway :-)

Update UI from a background worker

I want to port my client from Java Swing(Java client) to Android(Android client).
Basically, my Java client have a thread, which run a forever while loop to receive UDP packets, and base on content of UDP packets, UI of the corresponding JFrame will be updated.
Now I want my Android client has a background worker like the thread in the Java client, and that worker will be initialized in the main activity. Then when there are some requests from the UDP socket, the main activity will start some corresponding activities (Chat Activities), then there are some other requests come from the UDP socket, the worker will update on the activity(this activity can be main activity or a Chat Activity) which is being displayed on the screen.
So my question is what the background worker should be:
Service
Normal Java thread
Asynctask
or what...
Which is the most appropriate with my requirements?
Thanks!
The background worker should be a service, because
A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.
while your UI will be a activity, your service will read the UDP packets and the activity will be modified accordingly.
A Service is the most suitable candidate in your case.
There is a class Application class for each android application . First extend it and it will be initialized on very first time your app will start even before your Activity . Initialize/ start your normal java thread to perfrom background work here . The key advantage will be you can get instance of this application class anywhere from the app (It means you can control on the background thread from anywhere in the applicaion . Send background http request etc.. whatever ....) .Then initialize the handler on the UI thread of particular activity upon which you want to do changes and do something like this.
private Handler myHandler ;
public void checkBackgroundAndUpdateUi()
{
if(conetxt.getApplicationContext().getStatus == completed)
{
initializeHandler();
handler.postRunnable(myRunnable);
}
}
Runnable myRunnable = new Runnable(){
public void run()
{
// update your UI views here .....
}
};
private void initializeHandler(){
myHandler = new Handler ();
}

Categories

Resources