Lukis
Lukis

Reputation: 652

Refresh TextView after executing AsyncTask

I have problem with refreshing TextView after I get required data in AsyncTask. Everything would be fine if it was in single file, but I decided to split it. In first class I have TextViews and in another one I have few AsyncTasks which downloads data from net. What I've already tried:

mainActivity:

summary.countCash(); // it runs AsyncTask in summary class
while (summary.wait) {
    // do nothing and wait until AsyncTask finishes
}

eCash.setText("Cash: " + summary.cash);

and in AsyncTask:

Boolean wait = false;

@Override
protected void onPreExecute() {
    wait = true;
}

@Override
protected void onPostExecute(Integer result) {
    cash = result;
    wait = false;
}

Unfortunately it does not work. App freezes. I also tried to set

wait = false;

at the end of doInBackground, but then in main I got summary.cash = 0, which is probably because it refreshes TextView before value is updated in onPostExecute.

Upvotes: 0

Views: 403

Answers (2)

KarelG
KarelG

Reputation: 5234

uhm, i don't advise to keep stuck at a continuous loop. It will keep the Activity busy. Just invoke a callback method from the AsyncTask class.

in AsyncTask class

private _mainActivity;

// constructor
public AsyncTask(MainActivity ma) {
    // passing reference
    _mainActivity = ma;
}

@Override
protected void onPostExecute(Integer result) {
    _mainActivity.updateTextview(result);
}

and then in your MainActivity

public void updateTextview(Integer result) {
    // update textview using result
}

By this, your MainActivity wouldn't be stuck in a loop. Moreover, you can add a process dialog in the main activity and stop it in the updateTextview method.

edit 1

You can call it by using the AsyncTask class as object. I don't know the class name, assume it's AsyncTask then use the next in your MainActivity

AsyncTask at = new AsyncTask(this);
at.execute();

the this points to the MainActivity itself, which will be a reference. The AsyncTask class then can use the reference to invoke a callback method to the updateTextview() method.

Upvotes: 0

Nelson Ramirez
Nelson Ramirez

Reputation: 8004

In your async task.

@Override
protected void onPostExecute(Integer result) {
    eCash.setText("Cash: " + result);
}

Get rid of your while statement. You don't need it. Fyi, you are locking up the ui thread by waiting, defeating the purpose of the asynctask in the first place.

Hope this helps

Upvotes: 1

Related Questions