Utility classes in Android, AsyncTask, and loose-coupling please advise

Viewed 1336

I've attempted to search for any discussion on this topic, but I haven't found anything useful thus far. Therefore, I decided to go ahead and post this.

So my query is about Android best practices. I am creating a simple app that calls a RESTful end point, parses the downloaded JSON, and shows the results in some fragments contained within an activity.

I have a custom "utility" class that extends AsyncTask. In the doInBackground method, I make the request, store the response in a String, etc. (pretty simple stuff).

Now, I understand there are two other methods part of AsyncTask - onPreExecute and onPostExecute. If what I have researched online is correct, these methods are where I should be able to interact with the UI, by passing my context to this utility class, finding the view by id, setting the field text, or whatever it is that I want to do.

So that's my question is about. What is the best practice surrounding this?

Currently, my utility class that extends AsyncTask and makes the Web service call has a private member variable:

    private FragmentActivity mActivityContext;

And then, to interact with the UI, I do something like this:

@Override
protected  void onPreExecute()
{
    super.onPreExecute();
    android.support.v4.app.FragmentManager fm = mActivityContext.getSupportFragmentManager();
    MainActivity.PlaceholderFragment fragment = (MainActivity.PlaceholderFragment)fm.findFragmentByTag("PlaceholderFragment");

    if (fragment != null)
    {
        TextView textView = (TextView)fragment.getView().findViewById(R.id.my_custom_field);
        textView.setText("This field was updated through onPreExecute!");
    }
}

Although this seems to work okay so far, my concern is - should the utility class be accessing the fragment manager of the activity it has a reference to? Should it even have a reference to the activity? And by using the fragment manager, the utility class has to know the fragment tag. This isn't a very modular or loosely-coupled approach. Is the solution as simple as just passing in the fragment tag when I create the instance of the utility class instead of having it hard set like I do now? Or is there a better alternative route?

2 Answers
Related