user10387978
user10387978

Reputation:

Is it bad practice to pass an Activity as a Parameter? - Android

I am new to Android so am not quite familiar what is considered good/bad coding practice.

Is it considered bad practice to pass an Activity to as a parameter to say, another class?

Below is more or less what I am trying to do:

public class myClass {

    MyActivity activity;

    public myClass(MyActivity activity) {
        this.activity = activity;
    }

    // do something involving 'activity'
}

I find passing an activity as a parameter to my activity extremely useful as (A) instantly gives access to all properties in it, and (B) very clean; minimal lines of code to do so.

I understand that doing something like this considered "bad practice" in some languages. I was wondering if this was the case for Android? (or Java in general for that matter)

Upvotes: 1

Views: 751

Answers (2)

Sava B.
Sava B.

Reputation: 1047

You might make do with Context, which Activity inherits from. It makes more sense to pass the Context around, since that's kind of what happens with Context classes usually. Context is likely to have many of the methods you need.

public class myClass {

    Context context;

    public myClass(Context context) {
        this.context = context;
    }

    // do something involving 'activity'
}

The inheritance tree for activity:

java.lang.Object
   ↳    android.content.Context
       ↳    android.content.ContextWrapper
           ↳    android.view.ContextThemeWrapper
               ↳    android.app.Activity

https://developer.android.com/reference/android/app/Activity

Upvotes: 3

BlackHatSamurai
BlackHatSamurai

Reputation: 23483

It depends on what you are trying to do, but it can be appropriate. Sometimes you may only need the context of the Activity, rather than the activity itself. This is simply a form of dependency injection.

Upvotes: 2

Related Questions