I use appcompat v22.1.0 in my App and use Toolbar. Everything was fine when I use Theme.AppCompat.Light.NoActionBar
. When I start implement AlertDialog
Saw this same exception using Activity
and Theme.Light
theme. My problem was a wrong import, I was using the support one. import android.support.v7.app.AlertDialog;
instead of
import android.app.AlertDialog;
In my case, this crash was caused because I was passing View.getContext().getApplicationContext()
as Context
to the Builder
. This was fixed by using getActivity()
instead.
Adding Android:theme="@style/Theme.AppCompat" like this in manifest
<activity
android:theme="@style/Theme.AppCompat"
android:name=".MainActivity"
solved the problem
if you have this error when you creating a dialog (just in my case) you should use the following:
AlertDialog.Builder dialog = new AlertDialog.Builder(context, R.style.Theme_AppCompat_Light);
instead of:
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
This worked me perfectly!
Fixed my problem by using MainActivity.this (or YourActivityName.this)
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
Make sure you already Theme.AppCompat and extending AppCompatActivity.
If you are using support library your activity extends AppCompactActivity
, if you use android studio
to create activity this is default. In such case pass context to the builder as ActivityName.this
or simply this
if you are passing it in onCreate
, passing getApplicationContext()
will not work.
This is my style using appcompact
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:textSize">18sp</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
And everything is working fine when I use this
or ActivityName.this
as mentioned above (here ActivityName is the name of your current activity i.e. MainActivity.this
).
If you are using in fragment you should pass getActivity()
as context to builder instead of getContext()
.