Take the 2-minute tour ×

I have an issue where I need to access a method in my Activity from Android AsyncTask's onPostExecute() method

I have 2 Activities both contain a common method as below:

(1) Activity1 -- > refreshUI()
(2) Activity2 ----> refreshUI()

I got one AsyncTask call GetDataAsyncTask(Activity a ) which takes calling activity as argument

Now from my activity1 I will call new GetDataAsyncTask(Activity1.this).execute.
Same as above from my activity2 I will call new GetDataAsyncTask(Activity2.this).execute.

My AsyncTask is as below :

public class GetDataAsyncTask extends AsyncTask<String ,Void , String> {
    public Activity context;

    public PostAsyncTaskHelper(Activity c) { 
        context = c; 

    protected String doInBackground(String... arg0) {
        // Webservice calls 

    protected void onPostExecute(String result) {
        if(result.equals("qq")) {
            //Where I am not able to access refreshUI() 
            //method of any one of my activities

Can anyone help me how to get reference of any of the called activities from AsyncTask?

share|improve this question

3 Answers 3

up vote 2 down vote accepted

Define an interface for your Activities

public interface MyActivityRefreshInterface
 public void refreshUI();

your Activities must be defined as implements MyActivityRefreshInterface.

Your onPostExecute can then cast the context as (MyActivityRefreshInterface)context

share|improve this answer
make sure to review @wsanville comments re:reference to Activity, we both answered your question at same time with similar answers, but his answer more thoughtful –  CSmith Aug 8 '12 at 20:55

Make an interface that has the method refreshUI(), and make both Activity1 and Activity2 implement it. Then, you just need to typecast context to the type of the interface.

Also, you need to be careful about holding a reference to an Activity from inside an AsyncTask, because in the case of a config change (like screen rotation), you'll be holding on to a destroyed Activity instance. See here for details, and the corresponding example solution to this.

share|improve this answer

Because refreshUI is not a method in Activity. It is in your particular Acivity1 and Activity 2 classes, not the Activity class from Android. You should refactor so Activity1 and Activity2 to inherit from BaseActivity that has the refreshUI method on it and mark context in the AsyncTask as a BaseActivity

share|improve this answer

Your Answer


