j2me network connection - java-me

I have read in many places that network connection in a j2me app should be done in a separate thread. Is this a necessity or a good to have?
I am asking this because I could not find anywhere written that this must be done in a separate thread. Also, when I wrote a simple app to fetch an image over a network and display it on screen (without using a thread) it did not work. When I changed the same to use a separate thread it worked. I am not sure whether it worked just because I changed it to a separate thread, as I had done many other changes to the code also.
Can someone please confirm?
Edit:
If running in a separate thread is not a necessity, can someone please tell me why the below simple piece of code does not work?
It comes to a stage where the emulator asks "Is it ok to connect to net". Irrespective of whether I press an "yes" or a "no" the screen does not change.
public class Moo extends MIDlet {
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Display display = Display.getDisplay(this);
MyCanvas myCanvas = new MyCanvas();
display.setCurrent(myCanvas);
myCanvas.repaint();
}
class MyCanvas extends Canvas {
protected void paint(Graphics graphics) {
try {
Image bgImage = Image.createImage(getWidth(), getHeight());
HttpConnection httpConnection = (HttpConnection) Connector
.open("https://stackoverflow.com/content/img/so/logo.png");
Image image = Image.createImage(httpConnection
.openInputStream());
bgImage.getGraphics().drawImage(image, 0, 0, 0);
httpConnection.close();
graphics.drawImage(bgImage, 0, 0, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Edit: I got my answer for the code here.
Edit: I spawned off a separate question of this here.

The problem is that you are trying to do work within the thread that is responsible for running the UI. If you do not use a separate thread, then that UI thread is waiting while you do your work and can't process any of your other UI updates! so yes you really should not do any significant work in event handlers since you need to return control quickly there.

I agree with Sean, but it is not required to have your network connection in a separate thread, just best practice. I think that it's probably coincidental that the connection worked properly after moving it to a separate thread. Either way though, if you want to provide any visual feedback to the user while the connection is happening (which you probably do considering the disparity of lag that users can experience on a mobile network), you should have the networked processing in a separate thread.

It is not mandatory that you do network connections in a new thread,however practically you'll find that it almost always a good idea to do so since network activities could block and leave your app in an unresponsive state.
This is an old article but it speaks about some of the issues involved in networking and user experience.

Related

Leap Motion Controller.RemoveListener() called in Dispose() hangs

I've started developing a Leap Motion app and this is driving me nuts. Whenever I exit the application, the code responsible for cleaning up the Leap Motion controller hangs on me.
public void CleanUp()
{
_lmController.RemoveListener(_lmListener);
_lmController.Dispose();
}
I create both the controller and the listener in my Main Thread in a presenter class:
public MainViewPresenter(IMainView view, IApplicationController applicationController)
{
_view = view;
_applicationController = applicationController;
_view.Presenter = this;
_lmListener.Frame += _lmListener_Frame;
_lmController.AddListener(_lmListener);
}
The Cleanup() method is also a presenter method called on the view's FormClosing event. The weird thing is that it works perfectly fine when I call it from _listener_Frame(), which runs on a separate, Leap Motion-created no-name thread!
_lmListener_Frame() itself resides in the presenter. It just gets data from _lmController, creates a view model and sends it to the view, which in turn uses Invoke to update the display data.
I've tried calling the CleanUp stuff in Dispose() (both the view and the presenter (not redundant of course)) and that also doesn't work.
I admit that I'm not an expert in threading, but I can't see how there's any conflict going on here, and why RemoveListener works from controller thread, but not from the Main Thread, where the listener was actually added. Any help is appreciated!
SOLUTION
Completely by chance, I've found the solution today! It turns out that the "Invoke" call was the culprit, and it should've been BeginInvoke all this time, although this isn't mentioned anywhere in the WinForms setup guide. I'm guessing it was causing a deadlock with the controller thread and after the first GUI update it was bound to crash.
In a Windows forms Application, the following worked for me:
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
this.controller.RemoveListener(this.listener);
this.controller.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
}
I wrote it awhile ago, though, and don't remember why it needed to be more complicated than what you tried. (Full example here: https://developer.leapmotion.com/documentation/csharp/devguide/Project_Setup_WinForms.html)

javafx thread to update a listview

I'm trying to do a simple chat application on javafx
my actual problem is the thread to insert updates into a observablelist and set it on a listview
the code im using :
String message_reçu;
try {
out = new PrintWriter(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (true) {
message_reçu = in.readLine();
if (message_reçu != null) {
messagesReçus.add(message_reçu);
}
if (message_reçu.equals("QUIT")) {
break;
}
}
in.close();
out.close();
socket.close();
I did this inside of a runnable class and once the server fire a msg the thread insert the msg on the list and shows on the listview but the thread dies instead of keep the work
I did a search on it and every one says to use a runlater but I’m completely lost there I did declare a runlater but I’m not sure how to execute it so any help is welcome
Thanks
Other Answers
This question is largely a duplicate of the following questions, so also refer to the answers to those:
Usage of JavaFX Platform.runLater and access to UI from a different thread
Platform.runLater and Task in JavaFX
Solution
Your question is little more specific than those though, so I'll provide some extra info.
For your particular code you want to wrap the add call in Platform.runLater:
Platform.runLater(new Runnable() {
public void run() {
messagesReçus.add(message_reçu);
}
});
Everything else in your example stays as it is.
Background Information
JavaFX UI updates must be made on the JavaFX application thread or there is a high likelihood that your program will malfunction in unexpected ways.
The ListView control listens for changes to the ObservableList backing the ListView cell values. When that list changes, a UI update is immediately triggered on the thread the originally updated the list.
Once you wrap the list modifications in Platform.runLater, you ensure that the subsequently triggered UI update is performed on the JavaFX application thread rather than your user thread.

Java Thread Safety v Displaying a Dialog from separate Thread

Hi noticed some code in our application when I first started Java programming. I had noticed it created a dialog from a separate thread, but never batted an eye lid as it 'seemed to work'. I then wrapped this method up through my code to display dialogs.
This is as follows:
public class DialogModalVisibleThread
extends Thread {
private JDialog jDialog;
public DialogModalVisibleThread(JDialog dialog, String dialogName) {
this.setName("Set " + dialogName + " Visable");
jDialog = dialog;
}
#Override
public void run() {
jDialog.setVisible(true);
jDialog.requestFocus();
}
}
Usage:
WarnUserDifferenceDialog dialog = new WarnUserDifferenceDialog( _tableDifferenceCache.size() );
DialogModalVisibleThread dmvt = new DialogModalVisibleThread( dialog, "Warn User About Report Diffs");
dmvt.start();
Now, as far as I am now aware, you should never create or modify swing components from a separate thread. All updates must be carried out on the Event Dispatch Thread. Surely this applies to the above code?
EDT on WikiPedia
However, the above code has worked.
But lately, there have been countless repaint issues. For example, click on a JButton which then calls DialogModalVisibleThread to display a dialog. It caused buttons alongside the clicked button not to redraw properly.
The repaint problem is more frequent on my machine and not the other developers machine. The other developer has a laptop with his desktop extended onto a 21" monitor - the monitor being his main display. He is running Windows 7 with Java version 1.6.0_27.
I am running on a laptop with Windows 7 and Java version 1.6.0_24. I have 2 additional monitors with my desktop extended onto both.
In the meantime I am going to upgrade to Java 1.6 update 27.
I wondered if the above code could cause repaint problems or are there any other people out there with related paint issues?
Are there any easy ways to diagnose these problems?
Thanks
So, you're breaking a rule, having problems, and wondering if these problems could be cause by the fact that you broke the rule. The answer is Yes. Respect the rules!
To detect the violations, you might be interested by the following page: http://weblogs.java.net/blog/2006/02/16/debugging-swing-final-summary
The easiest way to check if your problems are being caused by breaking the rules is to fix them (You should fix them anyway :-)
Just use SwingWorker.invokeLater() from the thread you want to update to UI from to easily adhere to Swing's contract. Something like this should do the trick:
#Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
jDialog.setVisible(true);
jDialog.requestFocus();
}
});
}
EDIT: You should make the 'jDialog' variable final for this to work.

BluetoothChat synchronized onResume Activity lifecycle method, why?

I'm studying right now the bluetooth Android API, and I ran into the BluetoothChat example.
http://developer.android.com/resources/samples/BluetoothChat/index.html
It contains many errors, first of all the simple fact that it uses API 11 but manifest does not force this minimum API.
Other interesting thing is the use of synchronized keyword on Activity lifecycle methods, like on onResume:
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
Why this keyword is used there? Is there any reasonable explanation, or simply the one who wrote the code didn't know that onResume will be called always by the same thread? Or I miss something?
Thank you in advance!
This seems to be a pretty old question, but here's what I think may be going on:
My guess is that it wants to be careful about when "dialogs" return. The BluetoothChat example uses dialogs (as well as an overlay dialog-like activity) for enabling Bluetooth, enabling discovery, and initiating pairing/connections.
I don't know this for sure but I suspect there was a bug where different threads were returning to the main Activity and caused confusion as to how to handle onResume.
What they probably should have done is synchronize a block on an object and used flags to determine the state. That way the intention, state and functionality are more clear -- and the app knows what it should do in onResume;
something like this maybe:
//class fields
private Object myLockObj = new Object();
private boolean isPausedForPairing = false;
public void onResume()
{
super.onResume();
synchronized (myLockObj)
{
if (isPausedForPairing)
{
//handle a "pairing" onResume
}
}
}
However, due to it being an example app, they may have decided to go with something more simple. Example apps don't always follow convention because the idea is to demonstrate the particular code needed for the example. Sometimes following convention might add a lot of "distracting" code. Whether or not you agree with that is up to you though.

Handling threading and web requests on Windows Phone 7

How can you make a background web request and then update the UI, but have all the code that does the web requesting/parsing in a separate class so you can use it in multiple places? I thought I could use the classes methods as event handlers for a BackgroundWorker class, like
APIHelper mHelper = new APIHelper("http://example.com?foo=bar");
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork +=new DoWorkEventHandler(mHelper.GetResponse);
bw.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(mHelper.HandleResponse);
bw.RunWorkerAsync();
where APIHelper has the method
public void GetResponse(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker) sender;
WebRequest request = HttpWebRequest.Create(this.URL);
IAsyncResult result = (IAsyncResult)
request.BeginGetResponse(ResponseCallback, request);
}
but then I don't know how to access the worker thread from ResponseCallback and, anyway, HandleResponse gets called first (obviously). (I tried putting in result.AsyncWaitHandle.WaitOne(); but I get a NotSupportedException error.) Yet I can't work out how to make the web request call synchronously. I'm clearly trying to go about this the wrong way, but I have no idea what the right way is.
ETA:
My aim is to be able to go:
user clicks (a) button(s) (on various pages)
a "working" message is displayed on the UI thread (and then input is blocked)
in a background thread my APIHelper class makes the relevant API call, gets the response, and passes it back to the UI thread; I only seem to be able to do this by starting another thread and waiting for that to return, because there's no synchronous web requests
the UI thread updates with the returned message (and input continues as before)
I can do the first two bits, and if I have the response, I can do the last bits, but I can't work out how to do the middle bit. Hopefully that made it clearer!
It took me several tried before I found there is a Dispatcher.
During the BackgroundWorker's dowork and complete methods you can call:
this.Dispatcher.BeginInvoke(() =>
{
// UPDATE UI BITS
});
I think the Dispatcher is only available in the view. So I'm not sure if the methods can exist outside of the xaml.cs
Put whatever you want to update in your UI; when updating an ObservableCollection you must do the update of you items in the Dispatcher.BeginInvoke too
This link might be a good read too:
http://www.windowsphonegeek.com/articles/All-about-Splash-Screens-in-WP7-ndash-Creating-animated-Splash-Screen
Update to assist notes
This is just a rough idea mind you...
bw.DoWork +=new DoWorkEventHandler(DoWork);
bw.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(Complete)
// At least I think the EA is DoWork....
public void DoWork(object sender, DoWorkEventArgs e)
{
mHelper.GetResponse();
this.Dispatcher.BeginInvoke(() =>
{
UIObject.Visibility Collapse.
});
// Wait and do work with response.
});
}
public void Complete(object sender, RunWorkerCompleteEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
UIObject.Visible ....
});
}
I'd put all this logic in a viewmodel that the viewmodel of each page inherits from.
Have the pages bind to properties on the viewmodel (such as ShowLoading, etc.) which the model updates appropriately. i.e. before making the webrequest and in the callback.
As you won't be running the viewmodel code in the UI thread you also wouldn't need to run in a separate BackgroundWorker and you'll be able to access the properties of the viewmodel without issue.
It might be useful if you use a helper class that I have developed for WebDownload purposes during WP7 development.
I'm using it in 2-3 WP7 apps and no problem so far. Give it a go to see if it helps. You can get the class from the my blog linked bellow:
http://www.manorey.net/mohblog/?p=17#content
[NOTE] When working with this class you don't need to run anything in a background worker or new thread; it handles it all asynchronously.

Resources