26

May I know, is it safe for me to always cast Context to Activity within a View?

View {
    Activity activity = (Activity)this.getContext();
}

So far, it works fine all the moment. I was wondering, is there any edge cases that the above code will fail?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

4 Answers4

57

As I know, It is not always safe because, the context also can be passed from os to a Service, BroadcastReceiver, etc. But, almost of case, that is not a problem. just check with this code

if(context instanceof Activity)

and feel free to use.

lulumeya
  • 1,619
  • 11
  • 14
7

I think you can use following snippet:

/**
 * Get activity instance from desired context.
 */
public static Activity getActivity(Context context) {
    if (context == null) return null;
    if (context instanceof Activity) return (Activity) context;
    if (context instanceof ContextWrapper) return getActivity(((ContextWrapper)context).getBaseContext());
    return null;
}
Hexise
  • 1,520
  • 15
  • 20
3

Technically, Views can be created with any Context (via the LayoutInflater)

So unless you are super sure that your Views are only instantiated by Activities, I wouldn't suggest this. Doing this is not a clean idea.

Vikram Bodicherla
  • 7,133
  • 4
  • 28
  • 34
2

While I can't think of such case, I think it is not such a great idea for two reasons:

  1. Why would you want to do that, when do you explicitly need Activity?
  2. What if tomorrow this will be changed, and there will be other context for View?
MByD
  • 135,866
  • 28
  • 264
  • 277
  • 2
    **1.** There are [situations](http://stackoverflow.com/a/5376772) in which the caller can't an Activity as a parameter. **2.** Android is pretty good in keeping backward compatibility (which I can't say about its development tools). IMHO @lulumeya's answer is the correct answer to be accepted. – ateiob Aug 07 '12 at 20:19
  • `ContextThemeWrapper` certainly adds a whole new level of nonsense to it. I've heard you can access the Activity using `getBaseContext()` then. – EpicPandaForce Feb 09 '16 at 10:36