简体   繁体   中英

How to use one AsyncTask Class to apply different Activity in Android

I have a AsyncTask class that connect to web service to get something and then print to the screen.
Here is my code:

public class GetCreditAsyncTask extends AsyncTask<Object, Boolean, String>{
   private MainActivity callerActivity;
   private String credit;
   public GetCreditAsyncTask(Context context){
        callerActivity = (MainActivity )context;
    }
   @Override
    protected String doInBackground(Object... params) { 
         .....//do something and get the credit
}
   @Override
    protected void onPostExecute(String response) {
          callerActivity.txtView.setText(credit);
   }


}

It works perfect but now, I have one more Activity ProfileActivity
which also want to use GetCreditAsyncTask to get the credit and print it to the txtView ,
but at the begining of GetCreditAsyncTask , I cast the callerActivity to MainActivity .
The question is how to just use one AsyncTask class so that I can call it and get the credit.

You can define an interface that both activities implement. Instead of casting to MainActivity, you must cast to this interface.

public interface ActivityListener {
   public void setText(String text);
}


public class MainActivity extends Activity implements ActivityListener {

...

    public void setText(String text) {
        TextView tv = findViewById(R.id.main_text);
        tv.setText(text);
    }

}


public class SecondActivity extends Activity implements ActivityListener {

...

    public void setText(String text) {
        TextView tv = findViewById(R.id.secondary_text);
        tv.setText(text);
    }

}


public class GetCreditAsyncTask extends AsyncTask<Object, Boolean, String>{
   private ActivityListener callerActivity;
   private String credit;
   public GetCreditAsyncTask(Context context){
        callerActivity = (ActivityListener) context;
    }
   @Override
    protected String doInBackground(Object... params) { 
         .....//do something and get the credit
}
   @Override
    protected void onPostExecute(String response) {
          callerActivity.setText(credit);
   }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM