This article is more about Java Interfaces, rather than Android Development itself, but we will take an existing Android situation which we will deal with using Java.

The Problem

If AsyncTask class is implemented in a file outside an “Activity”, how can we make the “intent” call from inside the activity, rather than from the AsyncTask class’s “onPostExecute” method?

The problem here is quite clear.  Since our AsyncTask will be a separate java file, then the onPostExecute will be called from that file.  But we want this to run from the original Activity file that called the AsyncTask (whatever that activity file would be).

The Solution

We can approach this problem via interfaces.

For this solution, I have two files on GitHub (from a real project) that demonstrate the approach described here.  Please open these files from the real project, examine the code and keep up with my walkthrough at this article.

You can find both files at GitHub

In short, the solution consists of the following steps:
  1. Declare an interface for TaskCompleteListener in our AsyncTask file
  2. on onPostExecute, we set data to this listener
  3. implement this interface in MainActivity

So as a sample implementation, in our “EndpointsAsyncTask.java” we need to declare an interface like this

On AsyncTask class

public interface TaskCompleteListener {
    void onTaskComplete(String result);
}

private TaskCompleteListener mTaskCompleteListener;

public EndpointsAsyncTask(TaskCompleteListener listener) {
    mTaskCompleteListener = listener;
}

and then on the onPostExecute we need to add the following code

@Override
protected void onPostExecute(String result) {
    if (result != null) {
        mTaskCompleteListener.onTaskComplete(result);
    }
}

 

On Activity class

Now given the above, the class that calls the EndpointsAsyncTask implements the interface and takes care of the “intent call”.

The implementation on the activity calling this class would be something like this

public void tellJoke() {
    new JokeAsyncTask(new TaskCompleteListener() {
        @Override
        public void onTaskComplete(String result) {
            Intent intent = new Intent(MainActivity.this, DisplayJokesActivity.class);
            intent.putExtra(DisplayJokesActivity.EXTRAS_JOKE, result);
            startActivity(intent);   
    }).execute(this);
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.