Slurppa
Slurppa

Reputation: 33

Java AsyncTask passing variable to main thread

I have been trying to change textView after I'm done networking in an another thread with AsyncTask. I've tried countless solutions, but none have worked so far.

The only way I was able to achieve my goal was to use .get(), but it stops the UI thread for a while, and that's something I don't want.

I've also tried using the AsyncTask as an outer class, and using a wrapper class in the middle.

So my question here is, what is the easiest way to get hold of a variable used in doInBackground() and onPostExecute(), without freezing the main thread?

Upvotes: 2

Views: 2683

Answers (3)

Jejefcgb
Jejefcgb

Reputation: 390

Here is a way to do it. You can give a callback in parameter of your async task, do whatever you want and them get the value back from the async task.

Callback interface :

public interface AsyncTaskCompleteListener<T> {
    public void onTaskComplete(T result, int number);
}

AsyncTask :

public class LoadURL extends AsyncTask<String, Process, String> {

    private AsyncTaskCompleteListener<String> callback;

    public LoadURL(AsyncTaskCompleteListener<String> cb) {
        this.callback = cb;
     }

    protected void onPreExecute() {}

    protected String doInBackground(String... arg0) {
         // do something
        return content;
    }

    protected void onPostExecute(String content) {
        if (callback != null)
            callback.onTaskComplete(content,number);
    }
}

Activity :

public class LoginActivity extends Activity implements AsyncTaskCompleteListener<String> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        LoadURL loadUrl = new LoadURL(LoginActivity.this);
        loadUrl.execute(...);
    }

    @Override
    public void onTaskComplete(String result, int number) {...}
}

in onTaskComplete, you can easily modify your TextView

Upvotes: 3

sushantsha
sushantsha

Reputation: 81

You should return the variable from doInBackground(). Framework will make sure you will get the returned value in onPostExecute().

onPostExecute runs on the UI thread so you should be able to refresh any UI element here.

Upvotes: 1

Smashing
Smashing

Reputation: 1710

Just update the UI in the following code inside the AsyncTask:

@Override
protected void onPostExecute(Int result) {
  textView.setText(result.toString());
}

Check this link if you need extra help.

Upvotes: 1

Related Questions