contextthemewrapper cannot be cast to activity
From what I know, if a View that is shown in a Dialog, its context (access from view.getContext()) is actually a ThemeContextWrapper instance, which is probably not an Activity. To get the activity from the Dialog, you can use getOwnerActivity(), which returns the Activity that the Dialog belongs to.
Similar case I have. May be related question> Accessing activity from custom button
I solve my case with this snippet.
private static Activity scanForActivity(Context cont) {
if (cont == null)
return null;
else if (cont instanceof Activity)
return (Activity)cont;
else if (cont instanceof ContextWrapper)
return scanForActivity(((ContextWrapper)cont).getBaseContext());
return null;
}
Activity a= (Activity)(photoToLoad.imageView.getContext());
You can't assume a Context
can be casted to an Activity
. Hence the exception: You're attempting to cast a Context
that is in fact a ContextThemeWrapper
to an Activity
.
You can replace
Activity a= (Activity)(photoToLoad.imageView.getContext());
a.runOnUiThread(bd);
with e.g.
photoToLoad.imageView.post(bd);
to post a Runnable
to UI thread message queue, similar to Activity
runOnUiThread()
.
Kotlin solution in addition to kikea's answer.
fun Context.scanForActivity(): AppCompatActivity? {
return when (this) {
is AppCompatActivity -> this
is ContextWrapper -> baseContext.scanForActivity()
else -> null
}
}