Why does a dialog seemingly have its one thread? - java

I'm new to advanced programming - but from what I've read, all my android programs are on one thread.
This means, only one line of code or method/function can be executed at a time before moving on to the next line (that's what I thought anyway).
However, I'm using a custom dialog to develop this application and yet, the program continues even after the dialog has ran. I'd like my program to wait for the dialog to close so that I can receive the input and manipulate it.
This seems fairly straightforward when programming in Java (e.g. the Scanner tool waits for the user input before proceeding as opposed to running the code following it while it waits for user input).
How can I do this?

Everything does happen on one thread unless you explicitly tell it not to. However, showing a Dialog happens asynchronously. Basically, when you ask the Dialog to show, it adds that information to a list of UI events that are waiting to happen, and it will happen at a later time.
This has the effect that the code after asking the Dialog to show will execute right away.
To have something execute after a Dialog choice is made, add an onDismissListener to the dialog and do whatever it is you want to do in onDismiss.

Related

Other ways to perform tasks without loops?

I'm fairly new to java and I was creating a program which would run indefinitely. Currently, the way I have the program set up is calling a certain method which would perform a task then call another method in the same class, this method would perform a task then call the initial method. This process would repeat indefinitely until I stop the compiler.
My problem is when I try to create a GUI to make my program more user friendly, once I press the initial start button this infinite loop will not allow me to perform any other actions -- including stopping the program.
There has to be another way to do this?
I apologize if this method is extremely sloppy, I sort of taught myself java from videos and looking at other programs and don't entirely understand it yet.
You'll need to run your task in a new thread, and have your GUI stuff in another thread.
Actually, if you keep working on this problem, you'll eventually invent event driven programming. Lots of GUI based software, like Android, use this paradigm.
There are several solutions. The first that comes to mind is that you could put whatever method needs to run forever in its own thread, and have a different thread listen for user input. This might introduce difficulties in getting the threads to interact with each other, but it would allow you to do this.
Alternatively, add a method that checks for user input and handles it inside the infinite loop of your program. something like below
while(true){
//do stuff
checkForUserInput();
//do other stuff
}
To solve this problem, you need to run your UI in another thread.
Many programs are based on an infinite loop (servers that keep waiting for a new user to connect for example) and your problem isn't there.
Managing the CPU time (or the core) allocated to your infinite loop and the one allocated to take care of your UI interactions is the job of the operating system, not yours : that's why your UI should run in a separate thread than your actual code.
Depending on the GUI library (Swing, ...) you're using there may be different ways to do it and the way to implement it is well answered on Stack Overflow

Showing calculation progress real time and retain progress even if the browser is closed

Suppose, this is in any jsp with servlet project.
I clicked a button to calculate something, and the process will be done in a few steps or by using some synchronized threads that need nearly 5 hours.
If I close the browser window after a click, what will happen?
Will the calculation process stop or continue?
If its the latter (continue), and I log in to my account after 2 hours, what will I see?
I want to see the calculation progress real time.
What should i do?
This kind of processing requires planning. There are many edge cases. What if the process is already running? What to do if the server terminates in the middle of processing? Can you restart? Can the processing be interrupted? Can every user start this processing, or just authorized ones?
Ok, now to an answer. You want to run the processing in a separate, background thread. See the Executor classes. Then you have to store the progress of that processing somewhere (think db here) and create another page to show that progress. You may also have to remember the user that started the processing, so that you know which of the progress information to show to the user requesting the progress.
So, simple! :)

Handling mouse input in a Java card game

I've been working on a Java card game application where I'm trying to properly implement an MVC architecture for the sake of learning. Currently, I've implemented models for the deck, the table, and all of the players. I've also created viewer classes for each of the models, where each viewer displays its respective model in a JPanel. I then have a GameViewer class, which places all of the viewers into a JFrame.
My top-level class calls Main, which creates instances of all the models and viewers. I'm now trying to implement controllers, which will use the ActionListener class to look for button clicks from the user and modify the viewers and models accordingly. I'm confused though as to how best to do this.
The design of my game is very sequential, where the game displays a message to the user, then waits for the user's input from a mouse-click, then continues, etc. For this reason, I thought I would run the actual game in a while loop in Main, where each iteration represents a round in the game, until the game is over.
The issue is that I'm only interested in some inputs from the user at specific times. For instance, I might display a message to the user and tell them to click the OK button to continue. At this point, I don't care if they click on one of the cards, because I'm just looking for a click of the OK button. At other times, I may ask the user to choose a card, in which case, I'm waiting for them to click on a card, and I'm not interested in clicks from the OK button.
I'd like to implement this without any sort of polling, but I'm not sure the best way to do this. If I get to a point where I'm waiting for user input, do I use the wait() method to put the game thread to sleep until an event callback from an ActionListener sends a notification?
Otherwise, is using the sequential code in Main the wrong way to go about it? Should I be implementing all of the game logic within the event callbacks from the ActionListeners?
Thanks in advance.
My top-level class calls Main, which creates instances of all the models and viewers. I'm now trying to implement controllers, which will use the ActionListener class to look for button clicks from the user and modify the viewers and models accordingly. I'm confused though as to how best to do this.
The design of my game is very sequential, where the game displays a message to the user, then waits for the user's input from a mouse-click, then continues, etc. For this reason, I thought I would run the actual game in a while loop in Main, where each iteration represents a round in the game, until the game is over.
This is fine, but what I would do is make your game a step-wise game (I forget the name for this) where in the game loop you change the state of the program depending on the previous state and the user input. Then have your program's behavior state-dependent. To implement this, consider creating an enum to encapsulate program state and using a state design pattern to allow the program to alter behavior depending on its state.
The issue is that I'm only interested in some inputs from the user at specific times. For instance, I might display a message to the user and tell them to click the OK button to continue. At this point, I don't care if they click on one of the cards, because I'm just looking for a click of the OK button. At other times, I may ask the user to choose a card, in which case, I'm waiting for them to click on a card, and I'm not interested in clicks from the OK button.
And here is where a state pattern would shine since with it you would allow the user to click where ever he desires, but only have your program respond to certain clicks depending on the program's state.
I'd like to implement this without any sort of polling, but I'm not sure the best way to do this. If I get to a point where I'm waiting for user input, do I use the wait() method to put the game thread to sleep until an event callback from an ActionListener sends a notification?
Correct -- don't do polling and don't use wait() or anything else that might stop program flow.
Swing is an event driven environment, you can't control when these events might occur, the user may click on some part of your program or push a key, you really can't control this.
Swing uses a single thread (AKA The Event Dispatching Thread) or EDT), Swing uses to to dispatch events to interested parties as well as paint requests. Any action that blocks this thread will prevent the EDT from notifying your application of events or paint requests which will make your program "hang"
You can't think of GUIs as you would something like a console program, where the input is easy to control, instead you need to lead the user based on states of your controls and, Where required, dialogs.
So...NEVER, EVER create loop that blocks the EDTor performing long running or blocking (eg IO operations) that block this thread.
NEVER, EVER, create or modify any UI components from any thread other then the EDT.
You might like to have a read through
Creating a GUI With JFC/Swing
The Event Dispatch Thread
Concurrency in Swing
How to Make Dialogs

Determining onCreate() VS onRestartingFromBackGround() in Android app

I'm having a small problem with the Android app I'm designing.
I need to run some code whenever either of these 2 events happen:
1. The app is NOT running in the background, so the user launches it.
2. The app IS already running in the background, so the user is really
just re-opening it.
(I only need to run the code once, not twice.)
No matter where I put the call to my code (onCreate, onStart, onRestart, onResume, etc) I always have undesired affects:
A. My code gets run twice when #2 happens.
B. My code runs even when the user is just moving from
MAIN to a SUB-ACTIVITY, then back to MAIN again.
C. My code doesn't run at all.
Isn't there come kind of distinction I can make to determine: onCreate() and onRestartingFromBackGround()?
I thought I could use onRestart(), but I was VERY surprised to see that onRestart() runs even just when I do #B. (Is #B really considered a "restart" of my app????)
From a pure java standpoint, you could use a loading thread for when the icon is first pressed. This loading thread can poll the phone to see if the main activity thread is currently running or not, then from your loading thread, move to the correct piece of code. For ANDROID, I THINK, that you will poll the process name, or process ID...anyone ever poll the OS for processes??

Is there a function in Android analogous to "int main" in C/C++ which contains the program's main loop?

Normally in a C or C++ program there's a main loop/function, usually int main (). Is there a similar function that I can use in android Java development?
As far as an Android program is concerned there is no main().
There is a UI loop that the OS runs that makes calls to methods you define or override in your program. These methods are likely called from/defined in onCreate(), onStart(), onResume(), onReStart(), onPause(), onStop(), or onDestroy(). All these methods may be overriden in your program.
The fundamental issue is that the OS is designed to run in a resource constrained environment. Your program needs to be prepared to be halted and even completely stopped whenever the OS needs more memory (this is a multitasking OS). In order to handle that your program needs to have some of all of the functions listed above.
The Activity lifecycle describes this best (your program is one or more Activities, think of an Activity as a screen).
Bottom line: Your program 'starts' at onCreate() through onResume() but the OS is running the loop. Your program provides callbacks to the OS to handle whatever the OS sends to it. If you put a long loop at any point in your program it will appear to freeze because the OS (specifically the UI thread) is unable to get a slice of time. Use a thread for long loops.
In Android environment, there is no main(). The OS relies on the manifest file to find out the entry point, an activity in most case, into your application.
You should read http://developer.android.com/guide/topics/fundamentals.html for more detail.
According to:
http://developer.android.com/guide/tutorials/hello-world.html
The application class must support a method for each activity that the Application
supports. In the general case, the onCreate is probably equivalent to the main/top
function for your needs.
Maybe it's possible by creating a timer and execute custom functions at every tick, reset the timer when it's at a specific time
The above answers provide a "why" as to there's no "main loop" on Android (which is important to understand). I'll offer a solution to the implied question, instead, as many visitors here will be looking for exactly that.
I believe the appropriate thing to do, here, would be to create an AsyncTask which operates as your "main loop". Or better yet, design your main loop to run as a java.util.concurrent future, which can be started and ended during lifecycle events (like rotation!), using signaling (keep your data separate). The AsyncTask API is deprecated, because it was complex, and handling it properly amounted to writing code that would, effectively, operate as an AsyncTask which cleaned up when the next problematic lifecycle event transpired.
Keep in mind that this will be a separate thread from the UI, and, as such, will be required to respond in short order to UI thread events, like "onPause" and "onDestroy". If your app does not respond within a certain period of time (~5 secs, iirc) to these events, or user input events, it will be killed by the OS. It's really prudent, for a real-time app, to be able to fully respond to these events in under 1 sec, even on the lowest-end device. You can use synchronization primitives to notify other threads that their response is pending, and they can use them to signal when they are finished (or simply end, in the case of a future).

Categories