Search code examples
androidandroid-fragmentsandroid-asynctaskjava-threads

Accessing fragment objects from AsyncTask separate thread


I'm calling an asyncTask from a fragment to do some networking. While it is running i need to be able to disable the button in a fragment until AsyncTask calls onPostExecute.

my only problem is that i cannot access buttons like this from doInBackground:

Button mButtom = mActivity.findViewById(R.id.testButton);

it comes up with:

java.lang.RuntimeException: An error occured while executing doInBackground()
     at android.os.AsyncTask$3.done(AsyncTask.java:300)
     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
     at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.IllegalStateException: The current thread must have a looper!

Solution

  • We have our function called runOnUIThread

    @Override protected String doInBackground(String... strings) {
        activity.runOnUiThread(new Runnable() {
          @Override public void run() {
        //do your action
          }
        });
        return "";
      }