222

This one has me stumped.

I need to call an activity method from within a custom layout class. The problem with this is that I don't know how to access the activity from within the layout.

ProfileView

public class ProfileView extends LinearLayout
{
    TextView profileTitleTextView;
    ImageView profileScreenImageButton;
    boolean isEmpty;
    ProfileData data;
    String name;

    public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
    {
        super(context, attrs);
        ......
        ......
    }

    //Heres where things get complicated
    public void onClick(View v)
    {
        //Need to get the parent activity and call its method.
        ProfileActivity x = (ProfileActivity) context;
        x.activityMethod();
    }
}

ProfileActivity

public class ProfileActivityActivity extends Activity
{
    //In here I am creating multiple ProfileViews and adding them to the activity dynamically.

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile_activity_main);
    }

    public void addProfilesToThisView()
    {
        ProfileData tempPd = new tempPd(.....)
        Context actvitiyContext = this.getApplicationContext();
        //Profile view needs context, null, name and a profileData
        ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
        profileLayout.addView(pv);
    }
}

As you can see above, I am instantiating the profileView programatically and passing in the activityContext with it. 2 questions:

  1. Am i passing the correct context into the Profileview?
  2. How do I get the containing activity from the context?

16 Answers 16

507

From your Activity, just pass in this as the Context for your layout:

ProfileView pv = new ProfileView(this, null, temp, tempPd);

Afterwards you will have a Context in the layout, but you will know it is actually your Activity and you can cast it so that you have what you need:

Activity activity = (Activity) context;
21
  • 73
    You can't be guaranteed that the context you are working with is an Activity Context or an Application Context. Try passing an Application Context to a DialogView, watch it crash, and you will see the difference.
    – Sky Kelsey
    Commented Aug 1, 2012 at 23:10
  • 10
    Boris, the question asks if there is a way to get an Activity from a Context. This is not possible. Of course you can cast, but that is a last resort. If you want to treat the Context as an Activity, then don't downcast to an Activity. It makes for simpler code, and is less prone to bugs later when another person is maintaining your code.
    – Sky Kelsey
    Commented Aug 2, 2012 at 18:42
  • 6
    Note that 'getApplicationContext()' instead of 'this' will not work.
    – dwbrito
    Commented Jan 21, 2013 at 18:13
  • 1
    @BorisStrandjev I haven't quite understand your comment. Anyway, I said that after trying your example but instead of 'this' I used getApplicationContext() and the application tried to cast the App itself, hence giving a cast error, instead of the activity. After switching to 'this', as you answered, it worked.
    – dwbrito
    Commented Jan 22, 2013 at 23:06
  • 1
    The highest upvoted answers on your link both suggest challenging the question if it is smelly. This question certainly is smelly. The OP first stated: "I need to call an activity method from within a custom layout class." which is completely achievable with appropriate use of interfaces. Then he says "The problem with this is that I don't know how to access the activity from within the layout." which is a significant hint toward a misunderstanding. People try to to do the wrong thing all the time in programming and we shouldn't turn a blind eye to it.
    – Sam
    Commented Jun 3, 2015 at 14:16
61

This is something that I have used successfully to convert Context to Activity when operating within the UI in fragments or custom views. It will unpack ContextWrapper recursively or return null if it fails.

public Activity getActivity(Context context)
{
    if (context == null)
    {
        return null;
    }
    else if (context instanceof ContextWrapper)
    {
        if (context instanceof Activity)
        {
            return (Activity) context;
        }
        else
        {
            return getActivity(((ContextWrapper) context).getBaseContext());
        }
    }

    return null;
}
3
  • 1
    This is the right answer. The other ones don't take into account the ContentWrapper hierarchy.
    – Snicolas
    Commented Sep 26, 2017 at 15:07
  • This is the true answer:)
    – lygstate
    Commented Apr 16, 2018 at 17:05
  • 2
    @lygstate: What target API level are you using in your app? What is the error? This only works within the UI (activities, fragments, etc), not in Services.
    – Theo
    Commented Apr 16, 2018 at 19:45
35
  1. No
  2. You can't

There are two different contexts in Android. One for your application (Let's call it the BIG one) and one for each view (let's call it the activity context).

A linearLayout is a view, so you have to call the activity context. To call it from an activity, simply call "this". So easy isn't it?

When you use

this.getApplicationContext();

You call the BIG context, the one that describes your application and cannot manage your view.

A big problem with Android is that a context cannot call your activity. That's a big deal to avoid this when someone begins with the Android development. You have to find a better way to code your class (or replace "Context context" by "Activity activity" and cast it to "Context" when needed).

Regards.


Just to update my answer. The easiest way to get your Activity context is to define a static instance in your Activity. For example

public class DummyActivity extends Activity
{
    public static DummyActivity instance = null;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        // Do some operations here
    }

    @Override
    public void onResume()
    {
        super.onResume();
        instance = this;
    }

    @Override
    public void onPause()
    {
        super.onPause();
        instance = null;
    }
}

And then, in your Task, Dialog, View, you could use that kind of code to get your Activity context:

if (DummyActivity.instance != null)
{
    // Do your operations with DummyActivity.instance
}
7
  • 4
    +1 for explaining a very common area of confusion between the 2 different types of contexts (just like there are 2 different Rs). The Google folks need to enrich their vocabulary.
    – an00b
    Commented Jul 23, 2012 at 19:27
  • 3
    BTW, @BorisStrandjev is is correct: 2. Yes you can. (can't argue with working code)
    – an00b
    Commented Jul 23, 2012 at 20:31
  • 2
    2. Not really. If the context was the Application context, then your app would crash. Commented Jul 24, 2013 at 10:41
  • 29
    Creating a static reference to an Activity is the best way to create memory leaks.
    – BladeCoder
    Commented Jun 5, 2015 at 14:29
  • 1
    Static Activity reference is incorrect, activities are not singletons.
    – Miha_x64
    Commented Mar 7, 2017 at 16:28
15

And in Kotlin:

tailrec fun Context.activity(): Activity? = when {
  this is Activity -> this
  else -> (this as? ContextWrapper)?.baseContext?.activity()
}
2
9

If you like to call an activity method from within a custom layout class(non-Activity Class).You should create a delegate using interface.

It is untested and i coded it right . but i am conveying a way to achieve what you want.

First of all create and Interface

interface TaskCompleteListener<T> {
   public void onProfileClicked(T result);
}



public class ProfileView extends LinearLayout
{
    private TaskCompleteListener<String> callback;
    TextView profileTitleTextView;
    ImageView profileScreenImageButton;
    boolean isEmpty;
    ProfileData data;
    String name;

    public ProfileView(Context context, AttributeSet attrs, String name, final ProfileData profileData)
    {
        super(context, attrs);
        ......
        ......
    }
    public setCallBack( TaskCompleteListener<String> cb) 
    {
      this.callback = cb;
    }
    //Heres where things get complicated
    public void onClick(View v)
    {
        callback.onProfileClicked("Pass your result or any type");
    }
}

And implement this to any Activity.

and call it like

ProfileView pv = new ProfileView(actvitiyContext, null, temp, tempPd);
pv.setCallBack(new TaskCompleteListener
               {
                   public void onProfileClicked(String resultStringFromProfileView){}
               });
1
  • 1
    This is the correct answer and should be marked as the correct answer. I know the answer marked as the correct one actually answers OP's question, but it shouldn't be answering the question like that. The fact is that it's not good practice to pass in the Activity like that inside a view. The child should never know about their parent in any case, except through the Context. As Nepster states, the best practice is to pass in a callback, so whenever something happens of interest to the parent, the callback will be fired with the relevant data.
    – Darwind
    Commented Jun 27, 2018 at 13:52
7

Context may be an Application, a Service, an Activity, and more.

Normally the context of Views in an Activity is the Activity itself so you may think you can just cast this Context to Activity but actually you can't always do it, because the context can also be a ContextThemeWrapper in this case.

ContextThemeWrapper is used heavily in the recent versions of AppCompat and Android (thanks to the android:theme attribute in layouts) so I would personally never perform this cast.

So short answer is: you can't reliably retrieve an Activity from a Context in a View. Pass the Activity to the view by calling a method on it which takes the Activity as parameter.

4

Never ever use getApplicationContext() with views.

It should always be activity's context, as the view is attached to activity. Also, you may have a custom theme set, and when using application's context, all theming will be lost. Read more about different versions of contexts here.

2

I used convert Activity

Activity activity = (Activity) context;
1
  • 2
    There are different kind of contexts. Activities and Applications can have contexts. This will only work when the context is of a an activity.
    – cylov
    Commented Nov 15, 2017 at 14:42
2

For kotlin user -

val activity = context as Activity
2
  • This will crash if the context is ContextWrapper Commented Mar 3, 2023 at 2:03
  • @ravindu1024 exactly! here, context should be an instance of Activity
    – hasan
    Commented Mar 28 at 19:29
1

an Activity is a specialization of Context so, if you have a Context you already know which activity you intend to use and can simply cast a into c; where a is an Activity and c is a Context.

Activity a = (Activity) c;
2
  • 8
    This is dangerous because, as mentioned in a separate comment, the context may not always be an Activity.
    – user153275
    Commented Dec 30, 2014 at 16:57
  • 6
    typecast only if(context instanceof Activity){ //typecast}
    – Amit Yadav
    Commented Mar 26, 2015 at 8:51
1

I use this:

fun Context.findActivity(): Activity? = when (this) {
    is Activity -> this
    is ContextWrapper -> baseContext.findActivity()
    else -> null
}

or this:

fun Context.findActivity(): Activity {
    var context = this
    while (context is ContextWrapper) {
        if (context is Activity) return context
        context = context.baseContext
    }
    throw IllegalStateException("no activity")
}
0

This method should be helpful..!

public Activity getActivityByContext(Context context){

if(context == null){
    return null;
    }

else if((context instanceof ContextWrapper) && (context instanceof Activity)){
        return (Activity) context;
    }

else if(context instanceof ContextWrapper){
        return getActivity(((ContextWrapper) context).getBaseContext());
    }

return null;

    }

I hope this helps.. Merry coding!

1
  • Check that the context you passed in isn't null.. That's most likely the problem. Commented Oct 5, 2018 at 9:27
0

how about some live data callback,

class ProfileView{
    private val _profileViewClicked = MutableLiveData<ProfileView>()
    val profileViewClicked: LiveData<ProfileView> = _profileViewClicked
}

class ProfileActivity{

  override fun onCreateView(...){

    profileViewClicked.observe(viewLifecycleOwner, Observer { 
       activityMethod()
    })
  }

}

0

Create an extension function. And call this extension function with your context like context.getActivity().

fun Context.getActivity(): AppCompatActivity? {
      var currentContext = this
      while (currentContext is ContextWrapper) {
           if (currentContext is AppCompatActivity) {
                return currentContext
           }
           currentContext = currentContext.baseContext
      }
      return null
}
0

Kotlin android shorthand extension version of Theo's solution

private fun Context?.getParentActivity() : AppCompatActivity? = when {
    this is ContextWrapper -> if (this is AppCompatActivity) this else this.baseContext.getParentActivity()
    else -> null
}

Usage of above explained here

0

@rjrjr's solution actually runs into an IDE error:

Type checking has run into a recursive problem. Easiest workaround: specify types of your declarations explicitly

To fix this, use:

tailrec fun Context.getActivity(): Activity? = this as? Activity
    ?: (this as? ContextWrapper)?.baseContext?.getActivity()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.