0

I have a couple AsyncTask classes in my main activity, each of which fetches some small amount of data from outside, stores them in memory, and then calls a method in the main activity for displaying the data. I'd like to move these classes to their own files, but they reference methods and variables from the main activity. One solution someone mentioned was to pass the activity Context into the AsyncTask like so in order to call the activity methods you want:

((ActivityName)mContext).methodYouWant(...)
((ActivityName)mContext).varYouWant

Is this the right way to access methods/members of the main activity from an external class?

1 Answer 1

5

It'll work, but it's not great. Obviously it's inflexible and subject to future pain.

AsyncTask is nothing special, just a class. As such, how about having your Activity class define a listener interface, passing that listener into the constructor of your AsyncTask and calling the listener later?

public class MyActivity extends Activity {
    public interface AsyncTaskCompleteListener {
        public void onComplete(/* any data you want to share */);
    }

    ...

    private AsyncTaskCompleteListener myListener = new ...() {
        // do stuff with data
    }

    private MyAsyncTask extends AsyncTask<Something,Something,Something> {

         private AsyncTaskCompleteListener listener = null;
         public MyAsyncTask(AsyncTaskCompleteListener listener) {
             this.listener = listener;
         }

         protected void onPostExecute(Something result) {
             if(listener != null) {
                 listener.onComplete(/*params*/);
             }
         }
     }
 ...
 }

Just a thought.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the simple suggestion, I ended up using a similar approach to bridge the gap between the two.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.