Mes
Mes

Reputation: 1691

Avoid passing null to constructor as param

I have an AsyncTask in a separate file as DownloadImageAsyncTask.java and I'm passing, along with context, an ImageView as an argument to the constructor. When AsyncTask enters onPostExecute() method it assigns the image to the ImageView.

Later I realized I need to use the same code to another part of my app but instead of assigning the image to an ImageView I need to assign it as a background image to a FrameLayout.

Since duplication is the root of a lot of errors in Programming how can I re-use the AsyncTask so it can handle both cases and avoid copy/paste code ?

I tried with a constructor like :

public DownloadImageAsyncTask(Context context, ImageView ivCover, FrameLayout flCover) {
    this.context = context;
    this.ivCover = ivCover;
    this.flCover = flCover;
}

where I set either ImageView or FrameLayout as null but that doesn't feels right to me. (since I know that we should avoid passing null as a param)

Any ideas?

Upvotes: 0

Views: 344

Answers (2)

jseashell
jseashell

Reputation: 755

You can use what is called an overloaded constructor inside the DownloadImageAsyncTask class. It is very similar to how you can have several methods with the same name that take different parameters.

public DownloadImageAsyncTask(Context context, ImageView ivCover) 
{
    this.context = context;
    this.ivCover = ivCover;
}

public DownloadImageAsyncTask(Context context, FrameLayout flCover) 
{
    this.context = context;
    this.flCover = flCover;
}

To check the running instance of your result variable, you can do the following, although you may want to sprinkle in some null checks as well

if(result instanceOf ImageView)
{
    // do stuff
}
else if(result instanceOf FrameLayout)
{
    // do stuff
}
else
{
    // do other stuff
}

Upvotes: 1

Stanislav Bondar
Stanislav Bondar

Reputation: 6245

I would do with constructor override for seperate ImageView and FrameLayout. Then inside AsyncTask methods use Object as param and in onPostExecute(Object result) just check if(result instanceOf ImageView) else

Upvotes: 1

Related Questions