Long running process in separate thread updating UI - android

I noticed a similar problem for dot NET, but my problem is for Android, so perhaps solution looks different.
The process is activated by clicking button. The process was running as part of UI thread and at the end it did updating UI. I have added progress dialog to be more user friendly, so I instantiate a thread running the process and at the end it updates UI and dismisses progress dialog. Unfortunately UI update is failing with the exception below:
07-19 21:14:04.602: ERROR/Atjeews(283): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
If I try to block UI thread and release it after long process finishes to update UI, the progress dialog doesn't get shown. Should I try to show progress dialog in a separate thread instead, or there is another simpler solution?

please check http://developer.android.com/resources/articles/painless-threading.html

Taken from the Android Developers Processes and Threads page:
To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
You can just instantiate an anonymous Runnable as the argument, like post(new Runnable(){doWhatever();}), that will do whatever you want on the UI thread instead.

Related

ProgressBar in Android shows only after completing some operation

I tried to use ProgressBar in my Activity when I execute a short-time operation. And I realized that when I set ProgressBar visibility to true, It becomes visible only after the operation was executed.
progressBar.setVisibility(View.VISIBLE);
calculate();
Then I found the solution that I have to set ProgressBar visibility in another Thread. So my question is: why do I have to set it in another Thread?
For example, if I leave my ProgressBar with true visibility on creation (in onCreate()), it will progress and I can interact with UI in that moment. I concluded that they execute in one thread and It's okay. But It seems to me I'm wrong.
The Android UI toolkit is not thread-safe. This means that you must not manipulate your UI from a worker/background thread. you must do all manipulation to your user interface from the UI (Main) thread.
Android UI toolkit include elements in android.widget & android.view packages
Rule of Thumb:
Do not block the UI thread (don't run operations that have unspecified time in UI thread)
Do not access the Android UI toolkit from outside the UI thread
This is explained in more details in here
Running background threads using AsyncTask or Loaders always allow you to update your UI upon the background thread results in their onPostExecute() and onLoadFinished() respectively.
So, as of your question, you have to update your ProgressBar from the UI thread not from other threads.

Difference between android runOnUiThread and simple code in java

I am a beginner in android application development.I am working with threads in android.I have read about a runOnUiThread which run code on main UI(if i am not wrong?i guess.).
My question is what is the difference between normal code on main UI and code inside runOnIUThread.
Example:1
class A
{
getDataFromServer(foo);//Code on mainUI
}
Example:2
getActivity.runOnUiThread(new Runnable(){
#Override
public void run(){
getDataFromServer(foo);
}
});
What is difference in both example.Please help me.Your response will be a new learning for me.
Assuming that you meant simple code for UIThread code,
What is a thread ?
A thread defines a process running
First runOnUiThread ..
Runs the specified action on the UI thread. If the current thread is
the UI thread, then the action is executed immediately. If the current
thread is not the UI thread, the action is posted to the event queue
of the UI thread.
What is UIThread
Main thread of execution for your application
Most of your application code will run here onCreate, onPause, onDestroy, onClick, etc.
So simply Anything that causes the UI to be updated or changed HAS to happen on the UI thread
When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread.Now what if you want to do something that changes the UI?
Then you are welcome to runOnUiThread
You have to use runOnUiThread() when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler for the same thing.
Normally your code is executed on your UI thread. For longer taking tasks (such as network requests, etc...) you will use a background tasks (Handler, AsyncTask, Thread, ...).
As your Views can only be touched from a UI thread, you use runOnUiThread() if you are executing code in a background thread and you need to update your views, from this background thread.
To explain 'why' Android has the 'runOnUiThread()' option, it is important to understand that java is only used to create the bytecode (dex) that Android uses. The code running on the phone is NOT java.
Additionally, Android threads 'can' have a thing called a 'looper'. This 'looper' is what handles 'tasks(technically runnables and messages)' in order via a queue. The 'main ui thread' has by default a looper already attached to it.
That means that your runnable you created was put onto the looper's queue of the main UI thread. (this is why the runnable is NOT instantaneously ran, but will be ran 'quickly'/'soon')
The reason you'd use a runnable to run code on the UI thread is because you are in some other 'background thread' that you created... and want to update the UI in some way. (Only the UI thread can interact with the UI)

Android managging monitors concurrency with buttons

Context
I need to manage the concurrency of an app. I declared a Object sync to use monitors on that object.
The main goal is that the first button, A, will execute some code, but, when reaching some points, it needs button B to be clicked to be able to continue. Something like this:
Issues
The issue is that the B button can't be clicked, I guess it's because the UI thread is stuck waiting for the code of button A to be fully executed before raising other button events.
If I execute the code in button A in a new Thread, when I try to update the View (called UI in the drawing), I get CalledFromWrongThreadException.
Edit
I solved it adding a Handler for the UI update and the already added Thread for the code in A.
Factor the code that is taking the time into a Runnable that you execute in a separate thread, but once you've started that thread, do the UI update in the original thread.

Android: Blocking RPC with progress dialog

I have an Android App that uses an RPC mechanism to set/get information to/from a server. I call the RPCs from whithin the main thread (blocking) and I want them to be blocking. However, sometimes a call can last for some seconds and I'd like to display an indeterminate progress dialog after some specified time (e.g. 1 second).
I tried to spawn a new thread that makes the call and the main thread waits in a loop (with sleeps) until the call has been finished. Inside this loope I show the progress dialog but this is not working.
Is it possible to show and update the progress dialog inside another Thread or does anybody know a better solution that allows me to use blocking calls?
You cannot do both, make the main thread wait in a loop and show a progress dialog, at the same time. Either the main thread waits or shows the dialog.
Why do you want to block the main thread? Communication over the internet should always be done in a background thread because you never know how long it will take to complete. Do that stuff in AsyncTask and show the progress dialog in main.
Try using AsyncTask. It is an android mechanism which is used to make such network calls. Get the brief detailing of AsyncTask here:
Using AsynTask to show progress bar while attempting to SSH to Server
Using a AsyncTask you can block the user from proceeding ahead. You have to show a progress dialog in the onPreExecute() method of the AsyncTask. All your network related activities will take place in doInBackground(). After the background action is completed there will be a call to onPostExecute() where the progress dialog will be dismissed.
AsyncTask is a asynchronous call because you have 2 threads working simultaneously, one is the UI thread on which you are showing your progress dialog and the other is the non-ui background thread which is fetching your data from the server.
Hope this explanation helps.
I have found a solution that seems to work (at least I havent noticed any problems yet). I know the proper way would be to use somethn like AsyncTask but in my case I have no benefit from it and it complicates the program logic.
To update the UI within a new thread:
new Thread()
{
public void run()
{
Looper.prepare();
... do UI stuff here
Looper.loop();
}
}.start();

How to display a waiting dialog in android

I have a long task that requires 10 / 15 seconds. I want to display a dialog, or a view or other stuff to let the user know "hei! I'm working for you. I'm at 90%".
Actually I have 3 layouts: the currentLayout, the progressLayout and the resultLayout. From the main activity I have a function like that:
...
setContentView(R.layout.progressLayout );
SomeLongTask();
setContentView(R.layout.resultLayout);
...
but the progressLayout never shows.
What's the best way to do this?
You are starting the long Task in your User Interface Thread. This thread is also responsible for redrawing the UI and acting on Input Events. If you make a blocking call to the long task function your UI Thread will be busy to do the task and the User Interface can not change. The Android System even will think your Application crashed because it is not reacting to user input anymore.
You have to start the task in an AsyncTask and do all the heavy work in the doInBackground method and update your UI in the onPostExecute method. That way the UI Thread will start the task and then return to updating the Interface and acting on User Events.

Categories

Resources