Can't Touch Views From Onpostexecute's Asynctask
Solution 1:
Looking at the call stack, following call indicates that AsyncTask class was loaded on non-UI thread.
at android.os.HandlerThread.run(HandlerThread.java:60)
One of the Threading Rules mentioned in AsyncTask reference documentation is:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
Here is a bug related to this issue.
One of the solution is, load the AsyncTask
class manually in Application onCreate
method. This ensures the class gets loaded on main thread, before any application components uses it.
publicclassMyApplicationextendsApplication {
@OverridepublicvoidonCreate() {
try {
Class.forName("android.os.AsyncTask");
} catch (ClassNotFoundException e) {
}
super.onCreate();
}
}
Remember to specify MyApplication
in AndroidManifest
file.
Solution 2:
The solution in this answer should force the code to be run on the ui thread. It uses the Activity#runOnUiThread(Runnable)
function. Your code would end up like this:
@OverrideprotectedvoidonPostExecute(User[] users) {
if (isCancelled() || isFinishing()) return;
runOnUiThread(newRunnable() {
@Overridepublicvoidrun() {
findViewById(R.id.panelViews).removeAllViews();
findViewById(R.id.element).setText("something");
// ... more
}
});
}
Solution 3:
This occurs when you start an AsyncTask
from a background thread. The onPreExecute
and onPostExecute
don't automatically run on the main thread but in reality the thread the AsyncTask
was started from.
In other words, if you were already within a background thread when you called execute
on the AsyncTask
then that same thread is where the onPostExecute
method is called from meaning you would get that exception.
Solution 4:
Try this, This should solve your problem, perform your task in runOnUiThread()
@OverrideprotectedvoidonPostExecute(User[] users) {
runOnUiThread(newRunnable() {
publicvoidrun() {
if (isCancelled() || isFinishing()) return;
findViewById(R.id.panelViews).removeAllViews();
findViewById(R.id.element).setText("something");
}//run
}//runOnUiThread
}//onPostExecute
Post a Comment for "Can't Touch Views From Onpostexecute's Asynctask"