Skip to content Skip to sidebar Skip to footer

Creating A Callback Function Using Asynctask

I've created an AsyncTask class to handle sending and receiving from my server. What I'm trying to do is fire an event or callback when the data is received so I can use said data

Solution 1:

If you want to utilize a callback for an AsyncTask you can handle it via the following.

Do something like this (modifying your code to add what is below)

publicclassDataCollectClassextendsAsyncTask<Object, Void, JSONObject> {

    publicinterfaceOnDataCollectedCallback{
        voidonDataCollected(JSONObject data);
    }

    privateOnDataCollectedCallback mCallback;

    publicDataCollectClass(OnDataCollectedCallback callback){
        mCallback = callback;
    }

    // your code that is already there
    ...

    @OverridepubliconPostExecute(JSONObject response){
        if(mCallback != null)
            mCallback.onDataCollected(response);
    }
}

Then to make the magic happen

newDataCollectClass(newOnDataCollectedCallback() {
        @OverridepublicvoidonDataCollected(JSONObject data) {
            if(data != null)
                // DO something with your data
        }
    }).execute(requestURI, formVars);

However, it is worth noting, most networking libraries, including OkHttp, handle background threads internally, and include callbacks to utilize with the requests.

This also implements a custom interface, so others may be able to see how you could use this for any AsyncTask.

Solution 2:

There is a asynchronous get in OkHttp, so you don't need an AsyncTask, but as a learning exercise, you could define your callback as a parameter something like so.

newDataCollectClass(newCallback() {
            @OverridepublicvoidonFailure(Call call, IOException e) {
                // DO something on FAIL
            }

            @OverridepublicvoidonResponse(Call call, Response response) throws IOException {
                JSONObject collected = null;
                String jsonResponse = response.body().string();
                Log.d("Callback - Net", jsonResponse);
                try {
                    collected = newJSONObject(jsonResponse);
                    Log.d("Callback - Net", collected.getString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).execute(requestURI, formVars);

The AsyncTask

publicclassDataCollectClassextendsAsyncTask<Object, Void, Call> {
    privateCallback mCallback;
    privateOkHttpClient client;

    publicDataCollectClass(Callback callback) {
        this.mCallback = callback;
    }

    @OverrideprotectedvoidonPreExecute() {
        super.onPreExecute();
        this.client = newOkHttpClient();
    }

    @OverrideprotectedvoidonPostExecute(Call response) {
        if (response != null && this.mCallback != null) {
            response.enqueue(this.mCallback);
        }
    }

    @OverrideprotectedCalldoInBackground(Object... params) {

        // Get Parameters //String requestURI = (String) params[0];
        RequestBody formParameters = (RequestBody) params[1];
        Request request = newRequest.Builder().url(requestURI).post(formParameters).build();

        return client.newCall(request); // returns to onPostExecute
    }
}

Solution 3:

Call Webservice using asynctask is an old fashioned. You can use Volley or retrofit. But you can use this process to call Webservice . Here is steps:

  1. Create an Interface and implements it in your Activity/Fragment

    publicinterfaceIAsynchronousTask {
            publicvoidshowProgressBar();
            publicvoidhideProgressBar();
            public Object doInBackground();
            publicvoidprocessDataAfterDownload(Object data);
     }
    

Create Class DownloadableAsyncTask . This class is:

import android.os.AsyncTask;
import android.util.Log;

publicclassDownloadableAsyncTaskextendsAsyncTask<Void, Void, Object> {

    IAsynchronousTask asynchronousTask;

    publicDownloadableAsyncTask(IAsynchronousTask activity) {
        this.asynchronousTask = activity;
    }

    @OverrideprotectedvoidonPreExecute() {
        if (asynchronousTask != null)
            asynchronousTask.showProgressBar();
    }

    @OverrideprotectedObjectdoInBackground(Void... params) {
        try {
            if (asynchronousTask != null) {
                return asynchronousTask.doInBackground();
            }
        } catch (Exception ex) {
            Log.d("BSS", ex.getMessage()==null?"":ex.getMessage());
        }
        returnnull;
    }

    @OverrideprotectedvoidonPostExecute(Object result) {
        if (asynchronousTask != null) {
            asynchronousTask.hideProgressBar();
            asynchronousTask.processDataAfterDownload(result);
        }
    }

}

Now in your Activity you will find this methods.

DownloadableAsyncTask downloadAsyncTask;
ProgressDialog dialog;
    privatevoidloadInformation() {
            if (downloadAsyncTask != null)
                downloadAsyncTask.cancel(true);
            downloadAsyncTask = newDownloadableAsyncTask(this);
            downloadAsyncTask.execute();

        }

        @OverridepublicvoidshowProgressBar() {
            dialog = newProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
            dialog.setMessage(" Plaese wait...");
            dialog.setCancelable(false);
            dialog.show();

        }

        @OverridepublicvoidhideProgressBar() {
            dialog.dismiss();

        }

        @OverridepublicObjectdoInBackground() {
            // Call your Web service and return value

        }

        @OverridepublicvoidprocessDataAfterDownload(Object data) {
            if (data != null) {
                // data is here
            }else{
                //"Internal Server Error!!!"
            }

        }

Now just call loadInformation() method then you will get your response on processDataAfterDownload().

Post a Comment for "Creating A Callback Function Using Asynctask"