2

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?

Slurppa
  • 33
  • 1
  • 3

3 Answers3

3

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

Jejefcgb
  • 390
  • 3
  • 14
  • Is it possible to implement the interface to the main Class? When I try that, it just tells me the interface must be declared abstract, but doing so doesn't help. – Slurppa Mar 05 '15 at 06:52
  • I don't understand why the interface should be abstract. But if you want, you can put everything in the same file, but you'll have to remove the public attribute before the asynctask and the callback. Leave a comment if you need some help :) – Jejefcgb Mar 05 '15 at 08:40
1

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.

Smashing
  • 1,640
  • 18
  • 16
1

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.

sushantsha
  • 81
  • 1
  • 7