How to call a return value function in AsyncTask

I am new to andorid programming. I just found a problem to call the return value function inside AsyncTask. doInBackground() A simple question: how to wait for AsyncTask to complete and then execute the return statement without the user interface freezing, I also studied onPostExecute(), but it does not solve the problem. following code example

    public String hello()  {
String result = null;
 //calling asynctaske execute method
retrun result;
}
0
source share
2 answers

For myself, I do this using the callback function that I call after onPostExecute.

public AsyncUnzip(Activity ctx, Observer callback) {
    this.ctx = ctx;
    this.callback = callback;
}

and

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dia = new ProgressDialog(ctx);
    dia.setTitle("Bitte warten");
    dia.setMessage("Geodatenpaket wird entpackt...");
    dia.setCancelable(false);
    dia.show();
}

and

@Override
public void onPostExecute( Boolean result ) {
    super.onPostExecute(result);
    dia.dismiss();
    callback.update(null, returnFolder);
    System.out.println("Unzipped to: " + returnFolder.getName() );
}

In this case, your Async Task call will look like this:

AsyncUnzip unzipThread = new AsyncUnzip(ImportActivity.this, new Observer() {
    @Override
    public void update( Observable observable, Object data ) {//your code invoked after Async Task
} });
unzipThread.execute(selectedFile); //Start Unzip in external Thread.

Note. This is a quick and diry solution with an anonymous Observer implementation and no observable.

0
source

onPostExecute() AsyncTask BroadcastReceiver onPostExecute() AsyncTask. BroadcastReceiver, .

0

All Articles