AlertDialog - Activity vs Application Context

1.9k views Asked by At

Can someone please explain why I have to use my Activity's context in my AlertDialog.Builder parameter VS getApplicationContext()? Specifically, why am I getting this error:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

I understand the differences between the two but am wondering why specifically it mentions using Theme.AppCompat

I know that it has something to do with AppCompatActivity and themes no longer being compatible but can't quite find a solid explanation on why?

The theme of my app is set to this in the styles XML file:

    <style name="AppTheme" parent="Theme.AppCompat">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

Thank you

1

There are 1 answers

4
Sridhar On BEST ANSWER

There are two types of Context:

Application context is associated with the application and will always be same throughout the life of application -- it does not change. So if you are using Toast, you can use application context or even activity context (both) because toast can be displayed from anywhere with in your application and is not attached to a specific window. But there are many exceptions, one exception is when you need to use or pass the activity context.

Activity context is associated with to the activity and can be destroyed if the activity is destroyed -- there may be multiple activities (more than likely) with a single application. And sometimes you absolutely need the activity context handle. For example, should you launch a new activity, you need to use activity context in its Intent so that the new launching activity is connected to the current activity in terms of activity stack. However, you may use application's context too to launch a new activity but then you need to set flag Intent.FLAG_ACTIVITY_NEW_TASK in intent to treat it as a new task.

For more details