I'm trying to create a thread that keeps updating a TextView while the Main activity is running
I have used the Runnable class but it doesn't work
Every time my app crashes ...
Is there any way to do that ??
Please help
You may need this in your activity:
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText("something.");
}
});
or this:
textView.post(new Runnable() {
#Override
public void run() {
textView.setText("something.");
}
});
Both of these can let you change UI in work thread.
If you want to keep updating the UI regularly from a runnable, you could start an AsyncTask and update the TextView from postExecute function. postExecute always runs on the UI thread.
You can find more information here:
https://developer.android.com/reference/android/os/AsyncTask.html
Android doesn't allow you to change the UI from another thread. This is a OS design decision, meant to simplify UI handling. You can do whatever you want on secondary threads, but if you want to interact with views and widgets, you have to do it through the UI thread, as explained in the official documentation here.
Related
I come across both runOnUiThread and Handlers, but to me its still seems to be a doubt as on which facts do they differ exactly.
What would be the best way to update UI? Should I use runOnUiThread or Handler?
Already gone through link. Still not able to justify the difference.
Thank you in Advance
runOnUiThread is a method that uses main ui handler so basically they are the same. The only difference is that if you call it inside the ui handler, you just run it instead of post it.
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
Handlers are a nice way to implement an event queue. It doesn't have to run on the main thread, you can set your own looper. RunOnUiThread is basically a shortcut so you dont actually have the initiate a handler and so on.
Handler register itself in which it is declared. or you can set the looper manually also.
Handler is particular useful if you have want to post multiple times data to the main thread.
runOnUiThread is method of Activity. so when you need to update the UI Thread, you must write the code in the following way.
runOnUiThread(new Runnable() {
#Override
public void run() {
// update the ui
}
});
So there is no re-usability.
for example you want to update the status of the file downloading. you should write the above method multiple times.
But using Handler objects update the UI multiple times using same Handler Object.
I've got this piece of code:
public void updateOptionLists() {
Log.d("UI", "Called update");
if (updating){
return;
}
updating = true;
runOnUiThread(
new Runnable() {
#Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Log.d("UI","Updating");
}
});
Log.d("UI", "Posted update");
}
What I'd expect from logcat would be something like this:
Called update
Posted update
Updating
As far as I know runOnUi should be asynchronous, right? And considering that the functions called alter the views, which takes a while, this should be running asynchronous. Right?
So I look at my logcat:
Called update
Updating
Posted update
Why does this happen? And how do I make sure this runs asynchronous?
runOnUiThread will execute your code on the main thread, which (in this example) also appears to be where it's called from. This explains the ordering of the log statements you see - all code is executing on a single thread, so is synchronous per the documentation (my emphasis):
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.
runOnUiThread is typically used to execute code on the main thread from a different (i.e. background thread). The use of this separate background thread is what will make a task asynchronous. Calling back to the UI thread at the end of that task is required if you want to modify UI with the results of your background thread calculations.
Android provides several mechanisms for doing work on a background thread and then posting back to the main thread (not all use runOnUiThread explicitly for the latter operation). Good things to read up on include Thread, Handler, AsyncTask, Service, etc.
As far as I know runOnUi should be asynchronous, right?
runOnUiThread, as the name states, runs on UI thread, which is a main thread of an application. It runs synchronously with other code running within that thread and asynchronously with code in other threads.
The word 'asynchronous' has no meaning without a context: some code can run asynchronously with other parts of the code, which means these parts of the code run in different threads. Saying that something 'should be asynchronous' makes no sense without this kind of context.
is updateOptionLists running on the UI Thread?
If this is the case, i would expect this behavior to be ok.
In a normal case you use runOnUiThread from a background thread to come again to the Ui Thread..
Because you call upadetOptionLists() on ui prosess, upadetOptionLists() and runUiThread() both run in the same thread.
To separte theam you need run content in other new thread as following
public void updateOptionLists() {
new Thread(new Runnable() {
#Override
public void run() {
Log.d("UI", "Called update");
if (updating){
return;
}
updating = true;
runOnUiThread(
new Runnable() {
#Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Log.d("UI","Updating");
}
});
Log.d("UI", "Posted update");
}
}).start();
}
For accessing the view, you must be in the UI Thread (the main one). So, runOnUiThread will be executed on it.
You must do the long work in an other thread and only call runOnUiThread for little thing like changing a color or a text but not to calculating it.
From the documentation:
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.
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Multi Threaded Programming: Theory vs Actual
Puppy Photos Explain is the Best pic.twitter.com/adFy17MTTI— Cian Ó Maidín (#Cianomaidin) 6. april 2015
But joke aside.
If you want to test how the threads work in correlation, try:
runOnUiThread(
new Runnable() {
#Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Thread.sleep(100);
Log.d("UI","Updating");
}
});
I'm working for an Android app and implementing a ProgressBar by using AsyncTask class.
The problem is that on some devices, it causes "CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." in onPostExecute. On those devices, the problem occurs 100%. On other devices, it works fine.
public final class MyAsyncTask extends AsyncTask<String, Integer, String>
{
private ProgressBar progress;
private ListActivity activity;
public MyAsyncTask(ListActivity activity, ProgressBar progress)
{
this.progress = progress;
this.activity = activity;
}
protected void onPreExecute()
{
this.progress.setVisibility(view.VISIBLE);
}
protected String doInBackground(String[] arg0)
{
// getting xml via httpClient
return string;
}
protected void onPostExecute(String result)
{
this.progress.setVisibility(view.GONE);
}
I don't understand why onPostExecute does not run on the UI thread, on those certain devices.
Next, I tried to call it with runOnUiThread, to make absolutely sure that it runs on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
ProgressBar progress = (ProgressBar)findViewById(R.id.some_view_progressbar);
MyAsyncTask task = new MyAsyncTask(activity, progress);
task.execute();
}
} );
Even this did not solve the problem. The same exception still occurs.
From Log, I confirmed that Thread.currentThread().getId() is certainly different from the app's main activity's thread inside the handler.
I'm stuck. Any advice will be appreciated.
NOTE:I edited the sample code (not a real code) above to fix the wrong method name and missing "return string".
I will add more information later.
I don't see anything wrong with MyAsyncTask itself, but there are still other things that can go wrong.
Starting the AsyncTask
From the Android Docs
Threading rules
There are a few threading rules that must be followed for this class
to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
You don't show where you normally instantiate, and execute the task, so make sure that you do this in code that's already on the UI/main thread. Note that the first bullet point above might explain why this works for you on some devices, and not on others.
Creating the View Hierarchy
The message tells you
Only the original thread that created a view hierarchy can touch its views.
and you're assuming that this is because your async task is (strangely) trying to modify the UI on a background thread. However, it is possible that you get this error because the async task modifies the UI on the main thread, but the UI (ProgressBar) was not created correctly in the first place.
See this question for an example of how you can erroneously create the view on the wrong thread (anything other than the main thread), and get this same error.
More
I would, however, like to see exactly where you are logging the thread ID, and what value(s) you're getting. If you check out my first two suggestions, and they don't solve your problem, then we may need more information.
You also mention a Handler (?), but don't show how or where you use that. Normally, using AsyncTask removes the need to use Handler, so I'm a little worried about how you might be using that.
Update
Per the discussion in comments below, it looks like the issue here is the one discussed in this question. Some code, probably running on a background thread, is first to cause the AsyncTask class to be loaded. The original (pre-Jelly Bean) implementation of AsyncTask required class loading to occur on the main thread (as mentioned in the Threading Rules above). The simple workaround is to add code on the main thread (e.g. in Application#onCreate()) that forces early, deterministic class loading of AsyncTask:
Class.forName("android.os.AsyncTask");
Make sure you are invoking aysnctask.execute() from the main thread only.
Write a handler in UI thread and call the handler from onPostExecute. It will solve the problem.
Something like this. Have a handler in UI thread (main thread):
handler = new Handler(){
#Override
public void handleMessage(Message msg) {
//run on UI Thread
}
};
and call in onPostExecute() like this:
handler.sendEmptyMessage(MSG);
Is the sub thread can operate UI? Or it can only use handler to operate in main thread. But I use this code. It did not launch the error. Is anyone has ideas?
new Thread(new Runnable() {
public void run() {
TextView tv=(TextView) findViewById(R.id.aaa);
tv.setText("111");
}
}).start();
No, you cannot perform UI operation from a different thread. If you want to update the UI, you must use handlers. Alternatively you can also use async tasks or Activity.runOnUiThread.
Generally only the main thread should touch the UI. You are not promised to get an exception otherwise, but you are very likely to.
You should use handler / asyncTask / runOnUiThread as they are the ways to modify UI, other ways may work in some cases, but are not guaranteed.
In my Android app, I am extracting the code to update UI elements into a separate utility package for reuse. I would like my code to be proactive and update the UI differently if the current execution context is from a UI thread versus a non-UI thread.
Is it possible to programmatically determine whether the current execution is happening on the UI thread or not?
A trivial example of what I am looking to achieve is this - my app updates a lot of TextViews all the time. So, I would like to have a static utility like this:
public static void setTextOnTextView(TextView tv, CharSequence text){
tv.setText(text);
}
This obviously won't work if called from a non-UI thread. In that case I would like to force the client code to pass in a Handler as well, and post the UI operation to the handler.
Why don't you use the runOnUiThread method in Activity
It takes a runnable and either runs it straight away (if called from the UI thread), or will post it to the event queue of the UI thread.
That way you don't have to worry about if your method has been called from the UI thread or not.
When you're not sure the code is executed on the UI thread, you should do:
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
// your code here
}
});
This way, whether you're on the UI thread or not, it will be executed there.
You can use the View post method.
Your code would be:
tv.post(new Runnable() {
public void run() {
tv.setText(text);
}
});