4

I have a class NavActivity

public class NavActivity extends Activity implements OnItemLongClickListener {
....
}

In a function from another class, I have the following code:

    LocalActivityManager activityManager = this.getLocalActivityManager();
    Window window = activityManager.startActivity(tag, intent);

    final View view = window.getDecorView();
    Context decorContext = view.getContext();

    NavActivity nextActivity;
    nextActivity = (NavActivity)decorContext;

In previous versions of Android, everything has worked well. But in Android 7.0. it stops at this line and shows the following error:

Caused by: java.lang.ClassCastException: com.android.internal.policy.DecorContext cannot be cast to xxxxx.nav.NavActivity

Don't understand why casting from DecorContext into Activity does not work anymore in Android 7.0.

dimabin
  • 107
  • 1
  • 6
  • You can refer to this page: http://stackoverflow.com/questions/21657045/contextthemewrapper-cannot-be-cast-to-activity – ElixonPoker Apr 14 '17 at 08:26

2 Answers2

1

For this concrete example, I found the following solution:

I receive the needed activity by:

nextActivity = (NavActivity)activityManager.getCurrentActivity();

But in my project I anyway need to receive the correct View from Activity and then receive the View back from Activity.

Previously, getDecorView worked fine:

View view = activity.getWindow().getDecorView();

And back:

Activity activity = (Activity) view.getContext();

But in In Android 7 (Nougat) DecorView no longer knows to which Activity it's related to. It's not clear what to do then.

dimabin
  • 107
  • 1
  • 6
0

Because calling getContext on a View is not assured to return an Activity, it returns a Context. Sometimes Views initialized from xml are passed in a WrappedContext- a Context which wraps another context and overrides some values. It is never safe to assume that a Context will be an Activity. If it was working before then you got lucky- I've seen this kind of failure all the way down to at least 4.x

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • You very rarely need to pass an Activity in, generally connect is good enough. If you really do, pass it in explicitly rather than assuming the context will be it – Gabe Sechan Jan 23 '17 at 01:08