While executing the following code in an Android App, the setText happens after mainActivity.notify() is called from another Service. So, it appears as if the mainActivity.wait() is getting executed before the setText, resulting in the setText getting waited.
What may be the reason for this and how to make the Toast execute before mainActivity.wait(), so that the setText is displayed while the MainActivity waits.
public static Activity mainActivity;
....
startButton.setText("Processing...");
synchronized(MainActivity.mainActivity) {
try {
mainActivity.wait();
} catch (InterruptedException e) {
}
}
startButton.setText("Start");
First off, never have a static reference to an Activity. That's an almost assured memory leak. If you think you need that, your entire app's architecture is almost certainly wrong, or you don't understand how to use Contexts.
Secondly, under the hood Android, like any other GUI OS, is driven by an event loop. By holding up the main thread, you prevent the event loop from executing thus freezing the entire app. In particular without running the event loop the application will never redraw.
Third, you cannot wait until a Toast appears. Toasts are displayed by the system itself, and it does so when it decides to- there may be other toasts on screen already, for example. There is no mechanism to be informed of when a toast is displayed. The purpose of a toast is fire and forget, if you need something more powerful you'll need to write it yourself.
You can use Thread.sleep method
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Related
I'm trying to restrict the user from interacting with the program for a certain period of time, but sadly, with no success. I've tried using Thread.sleep, but as soon as the sleep action ends, the users' input catches up and keeps executing until it's finished.
For example, if I use the code below, the program will act as mentioned above: it'll sleep for the provided period of time (1,5s) and then the users' actions will catch up (it'll print "After waiting" as much times as the user clicked while the Thread.sleep was active). So how would I prevent this? Any suggestions would be greatly appreciated.
public void mouseClicked(MouseEvent e) {
print();
}
public void print() {
System.out.println("After waiting.");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The reason is that Thread.sleep() will block the UI Thread. So by clicking the first time, you will get an output and your application will store the following events from clicking again during the time for sleeping. Then, after your GUI-Thread comes back from sleeping, the events are released and some of the print-prompts are executed until it sleeps. Because
It is not very trivial to block the UI-Thread. If you want to prevent user input, you should disable the button or the Node in general which fires the event and enable it if its processing was finished.
First of all, I have almost no experience in Java. I'm using AsyncTask to get some data from my server and in the onPostExecute method I need to use several try-catch blocks to manage the received data. If one of them fails (catch is executed) the app should stop execution and show a dialog. But when any catch block is executed, the following try-catch blocks are executed, and that's what I want to avoid. I can't use return because onPostExecute returns void.
So, what is the best way to manage this situation to achieve what I need?
If a Method returns Void, you can use "return;" to exit the method.
So in the Catch block, Show the Dialogand Exit with return;
Elsewhere you can catch different exceptions in one try block.
I have an app and want to put the main thread to sleep for 1500ms, so I can show a ProgressDialog, but I don't know how to do it. It's possible to stop an app main thread? I can achieve the same goal using another thread right?
Stopping the main thread is usually a bad idea as it would also stop all UI interaction processing.
Try making the progress dialog modal. This will prevent the user from doing anything on your UI until the dialog is gone. I think this will achieve what you want to do and is compatible with how Android works
not a good idea to do this, but if you have to use this
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
//handle
}
Don't stop main UI thread! It will freeze UI. I can imagine that you show progress dialog during some background operation. Once this operation is complete just post something to update UI via handler.
The point of progress dialog is to interact with user while something long is executing. Otherwise you would not even need background operation and progress dialog. You would just do you operation in main UI thread and wait for UI to unfreeze.
What you're asking for should be unnecessary and as Carsten said, is a bad idea. It's a cardinal rule that you both never interrupt the UI thread and also only update elements of the UI on that thread. While a Dialog and any of it's subclasses are shown, nothing in the background will receive any input, so while it's up... though the main thread is running, nothing should be happening besides what is going on in the Dialog.
What you're probably looking to do is use something like an AsyncTask() to show your ProgressDialog, do some work, then dismiss it when that work is done.
To do something like this, you'll want to use "Runnables" along with a "Handler." As others mentioned, you don't want to stop the main UI thread. Since there is only one, you won't be showing ANY updates if you make it sleep or wait. See a small sample below of running code on another thread.
The main thing to take out of this is that sleeping the main thread means stopping any and all visual updates.
// Class Variables
private Handler mHandler;
#Override
public void onCreate(){
// Create a Handler Object
// In Layman's terms, Handlers can run processes off the main
// User interface thread.
mHandler = new Handler();
// Post a "Runnable" after a delay in milliseconds
// On a separate thread, the progressDialog_Runnable
// will call the function "createProgressDialog"
mHandler.postDelayed(progressDialog_Runnable, 250);
}
// Runnables (Process to run on separate thread)
private Runnable progressDialog_Runnable;
{
progressDialog_Runnable = new Runnable(){
#Override
public void run() {
createProgressDialog();
}
};
}
// Method you create to make the progress dialog
private void createProgressDialog(){
//... Run this code on a separate thread via Runnable
}
Sleep 10s on a thread in Kotlin
try {
Thread.sleep(10000)
} catch (e: InterruptedException) {
//handle
}
After having some trouble with setting up a thread to start my MIDI sequencer I decided to simply remove it, although it would slow my UI down I would be able to use it correctly.
What I noticed however was that even when playing the Sequencer the UI was very much active, even if it was playing around 500 notes the UI worked perfectly fine.
Now I know that in C# if you are doing something intensive it is advisable to load it on a new Thread as it will free the UI. Is it the same principle in Java, it's really confused me. If so can someone explain how the UI is not being blocked?
Thanks
Edit:
The following code actually plays the Sequence
public static boolean Play() {
if(!_sequencer.isRunning()) {
try {
_sequencer.setSequence(_sequence);
_sequencer.start();
return true;
} catch (Exception e) {
Logger.Add(e.getMessage());
}
}
return false;
//Already running
}
Yes, it is the same theory. Only the Event Thread can modify the UI, and thus if you are doing anything on that thread, then you are preventing other events from working on the UI.
It may be easier to think about the Event Thread as a queue:
Show Form
Click Button
Do your work (Action)
Reset focus of Button
Update Progress Bar
Et cetera
If #3 takes long, then it may mean that your form will appear locked up. Obviously it completely depends on your definition of long. In general, it's better to work off of the Event Thread rather than on it.
It's definitely the same principal. Generally speaking you want to only do minimal work with the UI thread. If it ends up taking any significant time, it can cause the UI to be unresponsive and you can get a "Not Responding" error. You want to keep the UI thread as free as possible so it can respond to user interaction.
If your application has a graphical user interface, it's advised that you perform expensive calculations on a new Thread to keep your graphics from freezing. You can either create a SwingWorker, or use the Callable/Future idiom.
Yes, you're right. Read Threads and Swing for more info.
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans. Netbeans now warns you not to use Thread.Sleep. So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.
So my question is how can I keep from using Thread.Sleep in the following situation.
I have written a server application that interfaces with another application. The server has two threads:
Handles the data coming over the socket and sends back other information or just plain acknoledgements.
This is the main thread. After kicking off the socket thread it going into an indefinite while loop. Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface. Then I sleep and continue this while loop.
With this application, the TrayIcon is the only UI.
Here is the snippet I'm referencing:
// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.
while(doNotExit())
{
if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
resetsThreadAndSocket();
try
{
// check to see if the socket threads are still active, if not create new ones.
if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
createSocketThread();
// check right before sleeping that the user does not want to exit.
if(getTrayIcon().isExiting())
break;
// puts the main Thread to sleep for 3 seconds
Thread.sleep(3000);
}
catch(SQLException ex)
{
_log.error(ex.getMessage(), ex);
restartDatabase();
}
}
The 'preferred' method in most cases would be to use the ScheduledExecutorService built into JavaSE for performing a periodic task, rather than reimplementing it yourself every time using a while loop and Thread.Sleep().
There's nothing wrong per-se with your example. The language just now has a much more robust support for doing that built into it as of Java 5.
Instead of your Thread.sleep(3000) do:
getPrimaryThread().join(3000)
This will wait for the thread to exit for 3 seconds.
You should consider attaching an event listener to your tray icon instead of polling its state. That way you won't need an extra thread just for monitoring.
If you can't do that for some reason, you can still do away with the extra thread as the Timer class can do the waiting for you.
You seem to be paranoid that some condition (maybe a RuntimeException or Error?) is going to cause your socket Thread to just die. Ideally, you would design your Socket Thread such that it protected itself from crashing. The following example creates a loop that can only be broken as a result of a JVM Error or Thread interrupt:
public void run() {
while(!Thread.currentThread.isInterrupted()) {
try {
//you application logic
} catch (RuntimeException e) {
//log uncaught exception
}
}
}
In order to shutdown the application, you would attach a listener to the TrayIcon which contained a reference to the SocketThread and could stop it by simply interrupting it.
socketThread.interrupt();
I'll leave figuring how to add an ActionListener to a TrayIcon up to you.