1

What is the proper way to subclass an AsyncTask so that it can be reused in multiple activities?

I have a multiple Activities that all use the same AsyncTask to get some JSON data. The only difference is that each Activity has it's own ProgressBar to show activty and its own processResult for processing the returned JSON data. I would like to subclass the AsyncTask so that I can pass in a reference to a ProgressBar so the appropriate Activity's ProgressBar's visibility is set and pass the returned data to that Activity's processResults().

Here is an abstract of a typical activity:

public class MyActivity extends AppCompatActivity {

    private ProgressBar mProgessBar;
    private List<Object> myList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mylayout);


        mProgessBar = (ProgressBar) findViewById(R.id.myProgessBar);
        myList = new ArrayList<Object>();

        getData();

    }

    private void getData() {
        //All async tasks take string variables
            new BGGetData().execute("Something", "Something", "Dark side", null);
    }

    private void processResults(JSONObject data) {
    //Different types of data for different activities.
        //process JSON results to fill myList or do something other action with the data
    }


    ///////
    //BACKGROUND TASK IS REPEATED IN MULTIPLE ACTIVITIES
    ///////
    public class BGGetData extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected void onPreExecute() {
            mProgressBar.setVisibility(View.VISIBLE);

        }

        @Override
        protected JSONObject doInBackground(String... params) {

            // do something to get a jsonobject

            return json; 
        }

        @Override
        protected void onPostExecute(JSONObject data) {
            mProgressBar.setVisibility(View.GONE);
            processResults(data);
        }

    }

}
user-44651
  • 3,924
  • 6
  • 41
  • 87
  • The linked answer shows that you can pass other values to the constructor so just pass your progress dialog there and whatever else you need. – codeMagic Jan 03 '17 at 18:32
  • @codeMagic The question you linked to doesn't show how to call the processResults for the calling activity. – user-44651 Jan 03 '17 at 18:36
  • [This one does](http://stackoverflow.com/questions/18517400/inner-class-can-access-but-not-update-values-asynctask) use a common interface to implement in the task class that you create. That one has an example with a link to another example. – codeMagic Jan 03 '17 at 18:41
  • Ahhh thanks! @codeMagic you can delete this question if you want. – user-44651 Jan 03 '17 at 18:47
  • You're welcome. No need to delete. It will help future users with the same issue to find the answers. – codeMagic Jan 03 '17 at 18:48

0 Answers0