1094

Android Studio 0.4.5

Android documentation for creating custom dialog boxes: http://developer.android.com/guide/topics/ui/dialogs.html

If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the <activity> manifest element:

<activity android:theme="@android:style/Theme.Holo.Dialog" >

However, when I tried this I get the following exception:

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

I am supporting the following, and I can't using something greater than 10 for the min:

minSdkVersion 10
targetSdkVersion 19

In my styles I have the following:

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

And in my manifest I have this for the activity:

 <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:theme="@android:style/Theme.Holo.Light.Dialog"
            android:name="com.ssd.register.Dialog_update"
            android:label="@string/title_activity_dialog_update" >
        </activity>

Creating the dialog box like this was something I was hopping to do, as I have already completed the layout.

Can anyone tell me how I can get around this problem?

Samuel Liew
  • 68,352
  • 105
  • 140
  • 225
ant2009
  • 30,351
  • 141
  • 365
  • 559
  • Are you using `AppCompat` from the support library? – Raghunandan Feb 16 '14 at 17:41
  • 2
    @Raghunandan, I am new to this but looking at my styles I have the following: – ant2009 Feb 16 '14 at 17:46
  • 14
    You are using `AppCompat` which is form the support library to support actionbars below api level 11. Just use `android:theme="@style/AppTheme" >` for the activity in manifest – Raghunandan Feb 16 '14 at 17:48
  • 2
    @ant2009, to claify what @Raghunandan said: in your `AndroidManifest.xml`, the theme you are specifying for your activity is overriding the theme you are specifying for your application. Remove the `android:theme` line from the `` tag. – cryptochronoconolite Feb 16 '14 at 18:00
  • @ant2009 you want a full screen dialog? – Raghunandan Feb 16 '14 at 18:05
  • 3
    Doing this will remove the error but not get him to where he wants to be which is an activity with a dialog theme. The general rule is that if you want your activity to have an action bar it should have the AppCompat theme and the java code should extend ActionBarActivity. If you have an activity that doesn't need an action bar (like a dialog themed activity) you can apply any theme to it but the java code must extend plain old activity. – Bobbake4 Feb 16 '14 at 18:05
  • I have come up with same error and solved this by https://stackoverflow.com/questions/29797134/how-to-use-and-style-new-alertdialog-from-appcompat-22-1-and-above – Shamin Meerankutty Jan 07 '18 at 09:57
  • 1
    I think the only problem in this case is the context you provide for Dialog constractor. See my answer. https://stackoverflow.com/a/51574281/232727 – Vitaliy A Jul 28 '18 at 18:54
  • If this error comes when you are using FragmentScenario to test your fragment using Espresso, then you can explicity pass R.style.Theme_AppCompat in the fragment scenario's launch method. – FingerSmith Oct 26 '20 at 13:02

52 Answers52

1163

The reason you are having this problem is because the activity you are trying to apply the dialog theme to is extending ActionBarActivity which requires the AppCompat theme to be applied.

Update: Extending AppCompatActivity would also have this problem

In this case, change the Java inheritance from ActionBarActivity to Activity and leave the dialog theme in the manifest as it is, a non Theme.AppCompat value


The general rule is that if you want your code to support older versions of Android, it should have the AppCompat theme and the java code should extend AppCompatActivity. If you have *an activity that doesn't need this support, such as you only care about the latest versions and features of Android, you can apply any theme to it but the java code must extend plain old Activity.


NOTE: When change from AppCompatActivity (or a subclass, ActionBarActivity), to Activity, must also change the various calls with "support" to the corresponding call without "support". So, instead of getSupportFragmentManager, call getFragmentManager.

Bobbake4
  • 23,485
  • 8
  • 55
  • 89
  • 6
    op is using appcompat in which case he should extend `ActionBarActivity` which is what is shown from his import statements from the comment below the quesiton. – Raghunandan Feb 16 '14 at 17:55
  • So I have now changed my class to extend activity i.e. public class MainActivity extends Activity {. However, I am still getting the same problem. – ant2009 Feb 16 '14 at 17:57
  • 1
    He's trying to create a dialog themed activity which would not have an action bar. You can easily do this when using the AppCompat library but you cannot if your activity extends ActionBarActivity. If he changes the java code to extend from Activity he will have a dialog themed activity like his question is requesting. @ant2009 shouldn't you be changing com.ssd.register.Dialog_update to extend from Activity not MainActivity? – Bobbake4 Feb 16 '14 at 17:58
  • @Bobbake4, thanks you was correct. I have changed the code as you specified. And now it is working. – ant2009 Feb 16 '14 at 18:08
  • @Bobbake4 is there any other workaround without changing the parent ActionBarActivity? – shanavascet Mar 29 '14 at 11:22
  • @shanavascet I'm not sure what you are asking here. Are you asking if there is a way to have an Activity inherit from ActionBarActivity without setting the theme to an AppCompat theme? If that is what you are asking no, you cannot extend ActionBarActivity without applying one of the AppCompat themes or extending one of those. – Bobbake4 Apr 07 '14 at 23:30
  • I'm getting this error, even when I have the Theme applied to my App thus: do I have to apply to all Activities individually as well? – Andrew Mackenzie Apr 15 '14 at 21:54
  • @Andrew Nope shouldn't have to. The docs for the application theme say this will be the default theme for all activities (http://developer.android.com/guide/topics/manifest/application-element.html#theme). If you want to create a new question with your manifest posted it might be easier to help diagnose. Link your question here. – Bobbake4 Apr 15 '14 at 22:01
  • Thanks @Bobbake4, that was my understanding also. The app compiles fine in IntelliJ and ant, and it's during my trying to mavenize it that I get the error. Probably something to do with the apklib dependency on the appcompat library....I'll need to investigate more myself first I think. – Andrew Mackenzie Apr 16 '14 at 06:49
  • Omg @Bobbake4! You're the real MVP! A question, I just created the app and this error was on the code, is that a bug? Or I'm missing something – sospedra Sep 25 '14 at 00:19
  • 2
    @Bursos If you're talking about when you create a new project in Android Studio I'm guessing that's a bug in the standard config. – Bobbake4 Sep 26 '14 at 17:29
  • Thanks @Bobbake4 so maybe we should report it. – sospedra Sep 26 '14 at 22:04
  • 2
    @Bobbake4, Im having the same problem, and this solution is impossible to work for me. The thing is that I can't extend Activity, because I have a bunch of classes (whole project) that relay on ActionBarActivity. Is there any other solution to the problem? Thx – 5er Nov 04 '14 at 09:40
  • 6
    @5er If your Java is using ActionBarActivity the theme must extend Theme.AppCompat. There are a handful of built in themes that do extend Theme.AppCompat or you could extend it yourself and modify it. Without removing the ActionBarActivity parent you cannot get around using the Theme.AppCompat. – Bobbake4 Nov 05 '14 at 15:20
  • 2
    @Bobbake4 thanks, for respond. I afraid that removing ActionBarActivity is not an option. But I have to show the activity as a Dialog. Do you have any idea how to do that? If I found any workaround how to use Theme.AppCompat I will let you know. – 5er Nov 13 '14 at 14:44
  • 29
    In style – Harmeet Singh Dec 01 '14 at 12:44
  • So why android studio generates MainActivity.java extending ActionBarActivity as default? – Peter Zhu Mar 14 '15 at 16:28
  • Thank you so much, you saved me time as from exceptions it was not clear where the problem is. I tried to changed android:theme in androidmanifest.xml then also in styles.xml and also in both but it still threw exception from which it was not clear how to make it working :) – damian1baran Jul 05 '15 at 11:11
  • 1
    http://stackoverflow.com/a/21492572/150371 might be a good solution to overcome this as well – raksja Aug 05 '15 at 04:42
  • 2
    This answer is not correct if you want to implement Chromecast and Mediarouter. See tutorial for this. You then need AppCompatActivity which need its corresponding theme. – carl Jul 17 '16 at 13:29
  • @carl This depends on what you are looking to do. If you look at the original posted question the user wanted to use theme `@android:style/Theme.Holo.Dialog` for his activity. If you want to do this your activity cannot extend AppCompatActivity. If you are getting this error and do not have a requirement of using that theme then you can update the theme to solve the issue, but I do believe this answer is correct for the original posted question. – Bobbake4 Jul 18 '16 at 13:10
  • If you change from ActionBarActivity to Activity, operation like getSupportFragmentManager() will not be able. So it's not the right answer. – Peter Aug 08 '16 at 12:06
  • 2
    @Peter - when you change from `AppCompatActivity` (or a subclass, `ActionBarActivity`), to `Activity`, you must change the various calls with "support" to the corresponding call *without* "support". So, instead of `getSupportFragmentManager`, call `getFragmentManager`. – ToolmakerSteve Feb 23 '17 at 20:48
  • 1
    Change ActionBarActivity is not a solution is a wrong workarround, because it affects the architecture of the Application. The solution is, as mentioned in other threads, to change contest for activity.this. – Christian Jun 06 '18 at 15:53
  • Mind that you have to import `android.app.AlertDialog` rather `android.support.v7.app.AlertDialog` – Sazzad Hissain Khan Jul 02 '19 at 04:41
575

All you need to do is add android:theme="@style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.

Michele La Ferla
  • 6,265
  • 11
  • 44
  • 75
iusting
  • 6,893
  • 2
  • 17
  • 28
  • 2
    In the code, ant2009 has AppTheme set as the application them which extends from a descendant of Theme.AppCompat. That should work. I had the same problem after upgrading to 5.0 on my device and ended up setting @style/Theme.AppCompat.Light as the theme on my activity. Something not right here... – speedynomads Nov 18 '14 at 00:21
  • I have a theme added to each activity and application. Still does not work. There is still more to it. – Martin Dec 26 '14 at 09:06
  • 37
    This is not a valid answer for Android Studio, though it in some cases it will work as a quick fix when one is bypassing styles.xml files. In Android Studio, proper way to define theme is to define them in styles.xml files, and then the Android menifest file will merely refer to them, and select them based on which Android version you are running on your device. Usually it is set to android:theme="@style/AppTheme" and this AppTheme refers to – zeeshan Jan 30 '15 at 22:43
  • This is basically deleting the reference to the Material theme. I don't think this helps getting anywhere. It's the same as saying NOT to use Material theme. – Radu Apr 08 '15 at 11:59
  • 5
    This didn't really work for me because my title bars disappeared when I used anything but holo... – AndyD273 May 12 '15 at 16:19
  • This would not allow me to change the background color of the ActionBar. It would igrnore whatever value I used. Until I changed the activity class from ActionBarActivity to Activity as mentioned in the top rated answer. – Loran May 24 '15 at 07:42
  • 1
    Ran into this issue as well using the SnackBar. This solved my issue. – worked Sep 23 '15 at 01:26
  • 2
    @Martin if you are like me, you have forget to add the same style name in general file styles.xml than you put in (V21) styles.xml file (without the properties specific to V21). If you declare a style in V21 folder and your device have a version below. It can't find it so an exception is fired. – letroll Apr 18 '16 at 08:59
295

Copying answer from @MarkKeen in the comments above as I had the same problem.

I had the error stated at the top of the post and happened after I added an alert dialog. I have all the relevant style information in the manifest. My problem was cured by changing a context reference in the alert builder - I changed:

new android.support.v7.app.AlertDialog.Builder(getApplicationContext())

to:

new android.support.v7.app.AlertDialog.Builder(this)

And no more problems.

Pang
  • 8,605
  • 144
  • 77
  • 113
A.K.
  • 3,385
  • 1
  • 15
  • 18
  • 5
    It happened with me also. I was just trying and your answer really worked! What is the logic for it to get worked? I really didn't understood. – kirtan403 Nov 26 '15 at 23:12
  • 6
    Or, if you are building your AlertDialog in a fragment, rather than directly in an Activity, use `getActivity()` rather than `this` as suggested above and the problem is fixed. As for why, I can only surmise the older AlertDialog.Builder(xxx) code either wanted a different type passed in, or was simply less picky about what got passed in, while the current Builder() really, really wants an Activity. Since Google has chosen to hide (remove?) the documentation for the old code, presumably in an effort to encourage use of the v7.app version, I know of no way to tell for sure. – Anne Gunn May 24 '16 at 21:34
  • Did the opposite of what is suggested. And it worked :P. Thanks! – Harisewak Sep 10 '16 at 11:25
  • 1
    This solve the program for me, also you would use `getContext()` instead of `this` if you're inside an ArrayAdapter or similar adapter class. – Ibrahim.H Nov 08 '17 at 14:22
  • In my onCreate I had been saving a member variable to hold context using getApplicationContext(). This answer led me to instead save context as "this", and crash went away. Thanks so much. – slogan621 Jan 25 '18 at 03:54
  • had the same issue, changed my style but still crashed. only worked after setting `this` to constructor – Manny265 Feb 19 '18 at 19:15
  • I knew completely this was the problem.. For those of you using builder in some listview(like me :P) `getApplicationContext()` is so tempting to use. Well this highlights with an error cannot be applied. Instead use **ActivityName.this**. Hope it helps for someone out there. – sanjeev Mar 25 '18 at 13:50
  • Thanks, this solved my issue, because I was calling this dialog from a different fragment, but the alert dialog needs to open from a floating action button which needs to be part of the main activity. – Janpan Mar 28 '18 at 20:05
  • I think this is the real answer. I have observed AlertDialog don't work with baseContext from Activity, but it workS with " this " . – jan4co Jan 17 '19 at 17:07
  • 2
    This is the genuine solution i ever meet. TIP: Please mention the difference in getApplicationContext() and this in this purpose. – prazeev May 20 '19 at 19:32
  • Same thing happened to me ,once I changed the "getApplicationContext()" to "Activity.this" everything went smooth. – Robotec Sep 10 '19 at 08:30
  • i'm here again in 2020. Your answer is my context doctor. – Kenny Dabiri Jun 29 '20 at 21:09
  • Thanks! I was using `AlertDialog` inside `Fragment`, all I had to do is give the builder `Activity` instead of `Context`. – Detained Developer Apr 08 '21 at 11:02
128

If you are using the application context, like this:

final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

change it to an activity context like this:

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
Darush
  • 9,625
  • 7
  • 53
  • 53
117

min sdk is 10. ActionBar is available from api level 11. So for 10 you would be using AppCompat from the support library for which you need to use Theme.AppCompat or descendant of the same.

Use

android:theme="@style/Theme.AppCompat" >

Or if you dont want action bar at the top

android:theme="@style/Theme.AppCompat.NoActionBar">

More info @

http://developer.android.com/guide/topics/ui/actionbar.html

Edit:

I might have misread op post.

Seems op wants a Dialog with a Activity Theme. So as already suggested by Bobbake4 extend Activity instead of ActionBarActivity.

Also have a look @ Dialog Attributes in the link below

http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4_r1/frameworks/base/core/res/res/values/themes.xml/

shareef
  • 7,886
  • 12
  • 53
  • 80
Raghunandan
  • 129,147
  • 24
  • 216
  • 249
  • Thanks for the suggestion. I did try that already actually. And I got the same problem. My styles file looks like this: – ant2009 Feb 16 '14 at 17:52
  • @ant2009 you won't. Use a theme from the support library AppCompat for your activity – Raghunandan Feb 16 '14 at 17:53
  • I not sure if I am adding this theme correct. But do you mean adding the following import statement? import android.support.v7.appcompat.*; However, I did try that and maybe I am wrong as I still ended up with the same exception. – ant2009 Feb 16 '14 at 18:05
  • @ant2009 you can have a custom dialog. But do you want to full screen dialog? – Raghunandan Feb 16 '14 at 18:06
  • I didn't want to have it full screen. Just a dialog box. However, the problem is solved now. Bobbake4 got it right. Thanks for you effort anyway, you have given useful advice. However, I am still confused with all this support library and AppCompat. – ant2009 Feb 16 '14 at 18:10
  • @Raghunandan Hi. please help me in one issue related with map using KML file – Piyush Sep 17 '14 at 06:36
  • Please see my question http://stackoverflow.com/questions/25886749/parsed-kml-file-doesnt-show-route-in-google-map-in-my-app – Piyush Sep 17 '14 at 09:48
50

I was experiencing this problem even though my Theme was an AppCompat Theme and my Activity was an AppCompatActivity (or Activity, as suggested on other's answers). So I cleaned, rebuild and rerun the project.

(Build -> Clean Project ; Build -> Rebuild Project ; Run -> Run)

It may seem dumb, but now it works great!

Just hope it helps!

Geraldo Neto
  • 2,864
  • 1
  • 22
  • 26
  • 1
    Had exact same message after adding DialogFragment to the AppCompat activity. File, Invalidate Caches / Restart fixed that in a pinch. – halxinate May 13 '16 at 07:18
  • 3
    I tried almost all answers in this thread. but only this seemingly "dumb" answer works. thank you! – Dika Oct 08 '19 at 16:13
  • When in doubt, assume Android Studio has silently corrupted your entire codebase and try rebuilding. This worked for me. Dear God, my hatred for Android knows no limit. – rmirabelle Dec 29 '20 at 21:34
27

This is what fixed it for me: instead of specifying the theme in manifest, I defined it in onCreate for each activity that extends ActionBarActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.MyAppTheme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity_layout);
...
}

Here MyAppTheme is a descendant of Theme.AppCompat, and is defined in xml. Note that the theme must be set before super.onCreate and setContentView.

k29
  • 1,715
  • 1
  • 14
  • 14
  • 1
    Robolectric is throwing a NullPointerException at the setTheme line when trying to load the resource. Any idea why? – Rhys Davis Feb 26 '15 at 20:34
  • @RhysDavis Difficult to say without stack trace, but perhaps it wants setContentView first? In that case this fix will not work for you. – k29 Feb 26 '15 at 21:36
23

go to your styles and put the parent

parent="Theme.AppCompat"

instead of

parent="@android:style/Theme.Holo.Light"
Yamen Nassif
  • 2,115
  • 2
  • 17
  • 40
  • Why can we do this with a standard activity. Did Android not put action bars on Standard Activities with ICS or Honecomb? Do we always have to use ActionBarActivity if we set our minimum target to SDK ICS? – Andrew S Nov 09 '16 at 06:25
  • how to see which theme we should use with the type or feature we are using because when we import we have all types of themes available – blackHawk May 13 '17 at 14:39
  • Thanks. This answer helped me. :) – Md Nakibul Hassan Jun 08 '20 at 16:50
17

Change the theme of the desired Activity. This works for me:

<activity
            android:name="HomeActivity"
            android:screenOrientation="landscape"
            android:theme="@style/Theme.AppCompat.Light"
            android:windowSoftInputMode="stateHidden" />
Eugene Gr. Philippov
  • 1,281
  • 2
  • 15
  • 15
sharma_kunal
  • 2,018
  • 1
  • 26
  • 27
16

In my case i have no values-v21 file in my res directory. Then i created it and added in it following codes:

  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
Ali Gürelli
  • 2,383
  • 2
  • 21
  • 33
14

I had such crash on Samsung devices even though the activity did use Theme.AppCompat. The root cause was related to weird optimizations on Samsung side:

- if one activity of your app has theme not inherited from Theme.AppCompat
- and it has also `android:launchMode="singleTask"`
- then all the activities that are launched from it will share the same Theme

My solution was just removing android:launchMode="singleTask"

goRGon
  • 4,104
  • 1
  • 41
  • 43
  • 2
    Just ran into this as well, I have not validated the fix and cannot reproduce the error.. but I am seeing this error in the wild on samsung devices only. most seem to be rooted as well, fwiw – danb Jun 13 '15 at 15:37
  • I had the error stated at top of post and happened after I added an alert dialog. I have all the relevant style information in the manifest. My problem was cured by changing a context reference in the alert builder - I changed: new android.support.v7.app.AlertDialog.Builder(getApplicationContext()) to: new android.support.v7.app.AlertDialog.Builder(this) and no more problems... – Mark Keen Aug 17 '15 at 20:29
  • Do you have any more details or links to samsung about this optimisation? Do all activities then have to implement Theme.AppCompat or there can be activities with no theme? – AAverin Apr 21 '20 at 11:36
14

Just Do

new AlertDialog.Builder(this)

Instead of

new AlertDialog.Builder(getApplicationContext())
Ali Akram
  • 2,966
  • 1
  • 18
  • 29
13

If you need to extend ActionBarActivity you need on your style.xml:

<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base"/>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->

If you set as main theme of your application as android:Theme.Material.Light instead of AppTheme.Base then you’ll get an “IllegalStateException:You need to use a Theme.AppCompat theme (or descendant) with this activity” error.

JonasOliveira
  • 720
  • 7
  • 21
12

I had the same problem, but it solved when i put this on manifest: android:theme="@style/Theme.AppCompat.

    <application
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name_test"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat">

        ...    

    </application>
Marc Baduq
  • 121
  • 1
  • 2
10

In my case such issue was appear when i tried to show Dialog. The problem was in context, I've use getBaseContext() which theoretically should return Activity context, but appears its not, or it return context before any Theme applied.

So I just replaced getBaseContexts() with "this", and now it work as expected.

        Dialog.showAlert(this, title, message,....);
Vitaliy A
  • 3,127
  • 1
  • 29
  • 30
9

I had an activity with theme <android:theme="@android:style/Theme.Dialog"> used for showing dialog in my appWidget and i had same problem

i solved this error by changing activity code like below:

@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_AppCompat_Dialog); //this line i added
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dialog);
}
Elyas Nategh
  • 472
  • 4
  • 4
  • 2
    This was a straightforward answer that worked for me without all the complexity and non-answer of the accepted one. – Cory Trese Dec 17 '18 at 15:55
9

for me a solution, after trying all solutions from here, was to change

    <activity
        android:name="com.github.cythara.MainActivity"
        android:label="Main">
    </activity>

to include a theme:

    <activity
        android:name="com.github.cythara.MainActivity"
        android:theme="@style/Theme.AppCompat.NoActionBar"
        android:label="Main">
    </activity>
Lucas Zanella
  • 223
  • 9
  • 35
8

You have came to this because you want to apply Material Design in your theme style in previous sdk versions to 21. ActionBarActivity requires AppThemeso if you also want to prevent your own customization about your AppTheme, only you have to change in your styles.xml (previous to sdk 21) so this way, can inherit for an App Compat theme.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

for this:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
danigonlinea
  • 1,013
  • 1
  • 14
  • 17
8

for me was solution to use ContextThemeWrapper:

private FloatingActionButton getFAB() {
Context context = new android.support.v7.view.ContextThemeWrapper(getContext(), R.style.AppTheme);
FloatingActionButton fab = new FloatingActionButton(context);
return fab;}

from Android - How to create FAB programmatically?

Community
  • 1
  • 1
Peter
  • 180
  • 3
  • 3
8

I had this problem as well and what I did to fix it, AND still use the Holo theme was to take these steps:

first I replaced this import:

import android.support.v7.app.AppCompatActivity;

with this one:

import android.app.Activity;

then changed my extension from:

public class MyClass extends AppCompatActivity {//...

to this:

public class MyClass extends Activity {//...

And also had to change this import:

import android.support.v7.app.AlertDialog;

to this import:

import android.app.AlertDialog;

and then you can use your theme tag in the manifest at the activity level:

android:theme="@android:style/Theme.Holo.Dialog" />

and lastly, (unless you have other classes in your project that has to use v7 appCompat) you can either clean and rebuild your project or delete this entry in the gradle build file at the app level:

compile 'com.android.support:appcompat-v7:23.2.1'

if you have other classes in your project that has to use v7 appCompat then just clean and rebuild the project.

Wraithious
  • 365
  • 2
  • 11
8

Make sure you are using an activity context while creating a new Alert Dialog and not an application or base context.

Shivam Dawar
  • 343
  • 4
  • 6
7

I was getting this same problem. Because i was creating custom navigation drawer. But i forget to mention theme in my manifest like this

android:theme="@style/Theme.AppCompat.NoActionBar"

As soon i added the above the theme to my manifest it resolved the problem.

Bryan J. Diaz
  • 336
  • 2
  • 8
Azhar osws
  • 188
  • 1
  • 8
6

Change your theme style parent to

 parent="Theme.AppCompat"

This worked for me ...

Fazal
  • 2,966
  • 1
  • 12
  • 20
6

You have many solutions to that error.

  1. You should use Activity or FragmentActivity instead of ActionbarActivity or AppCompatActivity

  2. If you want use ActionbarActivity or AppCompatActivity, you should change in styles.xml Theme.Holo.xxxx to Theme.AppCompat.Light (if necessary add to DarkActionbar)

If you don't need advanced attributes about action bar or AppCompat you don't need to use Actionbar or AppCompat.

Kaloglu
  • 1,233
  • 1
  • 16
  • 28
6

In Android manifest just change theme of activity to AppTheme as follow code snippet

<activity
  android:name=".MainActivity"
  android:label="@string/app_name"
  android:theme="@style/AppTheme">
</activity>
maxhb
  • 7,819
  • 9
  • 25
  • 50
shikha
  • 61
  • 1
  • 1
6

This is when you want a AlertDialog in a Fragment

            AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
            adb.setTitle("My alert Dialogue \n");
            adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                  //some code

            } });
            adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                 dialog.dismiss();

                } });
            adb.show();
Avinash_ks
  • 163
  • 3
  • 8
6

In my experiences the problem was the context where I showed my dialog. Inside a button click I instantiate an AlertDialog in this way:

builder = new AlertDialog.Builder(getApplicationContext());

But the context was not correct and caused the error. I've changed it using the application context in this way:

In declare section:

Context mContext;

in the onCreate method

mContext = this;

And finally in the code where I need the AlertDialog:

start_stop = (Button) findViewById(R.id.start_stop);
start_stop.setOnClickListener( new View.OnClickListener()
     {
                @Override
                public void onClick(View v)
                {
                    if (!is_running)
                    {
                        builder = new AlertDialog.Builder(mContext);
                        builder.setMessage("MYTEXT")
                                .setCancelable(false)
                                .setPositiveButton("SI", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                    Task_Started = false;
                                    startTask();
                                    }
                                })
                                .setNegativeButton("NO",
                                        new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
            }
        }

This is the solution for me.

Dante
  • 89
  • 1
  • 2
  • You're correct that you shouldn't be using an Application context the way you originally had it. What you've done is use an Activity as the context instead. This is not, however, an Application context or a subclass of it. So it's not right to say you're using an Application context in a different way. – Hod Mar 12 '18 at 22:28
5

This one worked for me:

<application
           android:allowBackup="true"
           android:icon="@mipmap/ic_launcher"
           android:label="@string/app_name"
           android:theme="@style/AppTheme" >
           <activity
               android:name=".MainActivity"
               android:label="@string/app_name"
               android:theme="@style/Theme.AppCompat.NoActionBar">

               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />

                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>
           </activity>
</application>
user1501382
  • 1,035
  • 13
  • 16
5

Your Activity is extending ActionBarActivity which requires the AppCompat.theme to be applied. Change from ActionBarActivity to Activity or FragmentActivity, it will solve the problem.

If you use no Action bar then :

android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" 
Md Imran Choudhury
  • 6,954
  • 2
  • 45
  • 50
4

Quick solution.

Change your base theme parent in styles.xml

Replace from

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

to

<style name="AppTheme" parent="Theme.AppCompat">
Kaloglu
  • 1,233
  • 1
  • 16
  • 28
3

This solution worked for me.

Design library depends on the Support v4 and AppCompat Support Libraries, so don't use different version for appcompat and design library in gradle.

use

 compile 'com.android.support:appcompat-v7:23.0.0'
 compile 'com.android.support:design:23.0.0'

instead of

 compile 'com.android.support:appcompat-v7:23.0.0'
 compile 'com.android.support:design:23.1.0'
kiran boghra
  • 3,062
  • 2
  • 16
  • 23
3

For me none of the above answers worked even after I had Theme.AppCompat as my base theme for the application. I was using com.android.support:design:24.1.0 So I just changed the version to 24.1.1. After the gradle sync, Its working again and the exception went away. Seems to me the issue was with some older versions of design support libraries.

Just putting this here in case other answers don't work for some people.

Sharp Edge
  • 3,895
  • 2
  • 23
  • 38
3

In my case, i was inflating a view with ApplicationContext. When you use ApplicationContext, theme/style is not applied, so although there was Theme.Appcompat in my style, it was not applied and caused this exception. More details: Theme/Style is not applied when inflater used with ApplicationContext

Bryan J. Diaz
  • 336
  • 2
  • 8
Murat
  • 2,891
  • 32
  • 47
3

When You're Using Kotlin, nothing solved my problem until I change the Builder parameter from 'applicationContext' to 'this'.

This Does Not Work

val dialogDelete = AlertDialog.Builder(applicationContext)
            .setTitle("Confirmation")
            .setMessage("Delete this photo?")
            .setNegativeButton(android.R.string.no){ it, which ->
                it.dismiss()
            }
dialogDelete.show()

Following Code Works

val dialogDelete = AlertDialog.Builder(this)
            .setTitle("Confirmation")
            .setMessage("Delete this photo?")
            .setNegativeButton(android.R.string.no){ it, which ->
                it.dismiss()
            }
dialogDelete.show()
RAINA
  • 314
  • 4
  • 17
Irfandi D. Vendy
  • 594
  • 9
  • 18
3

If you are struggling with the Recyclerview Adapter class then use

view.getRootView().getContext()

instead of

getApplicationContext() or activity.this
H A Tanim
  • 109
  • 1
  • 6
2

My Activity with SectionsPagerAdapter and ViewPager & Fragment

public class MyActivity extends AppCompatActivity implements ActionBar.TabListener
...
...
     @Override
        public void onPostResume(){
            super.onPostResume();
            try {
               getSupportActionBar().setDisplayShowTitleEnabled(false);
            }catch (NullPointerException ignored){
            }
        }
valera
  • 21
  • 2
2

In Android Studio: Add support library to the gradle file and sync. Edit build.gradle(Module:app) to have dependencies as follows:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.1'
    implementation 'com.android.support:design:23.1.1'
    implementation 'com.android.support:support-v4:23.1.1'
}

My support Library version is 23.1.1; use your support library version as applicable.

m02ph3u5
  • 2,735
  • 6
  • 34
  • 45
CodeBulls Inc.
  • 436
  • 3
  • 11
2

For me issue resolved by changing the inheritance from AppCompatActivity to Activity in my customDialog class. No changes required in manifest for Theme.Dialog.

vivek
  • 101
  • 2
  • 15
2

This really forced me to post my own answer.

Since I am using Theme.AppCompat.Light.NoActionBar, and also replaced all AlertDialog instances with support compatibility imports and still faced problems below v21 (Lollipop).

I didn't like the idea of changing the theme which was proper. So after 2 days, I finally gave some thought about the other libraries that are specifying AppTheme for their AndroidManifest.xml.

I found out that there is yet another one: Paytm Checkout SDK.

Thus, the following changes fixed the problem.

  1. Renaming AppTheme using for my app to 'XYZAppTheme'

  2. using tools:replace method in AndroidManifest of my project(app).

    <uses-permission android:name="android.permission.INTERNET" />
    
    <application
        android:name=".XYZ"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher_v2"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher_v2_round"
        android:supportsRtl="true"
        android:theme="@style/XYZAppTheme"
        tools:replace="android:icon,android:theme">
    
        <activity
            android:name=".xyz.SplashActivity"
            android:launchMode="singleTask"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
Amit Tumkur
  • 2,437
  • 23
  • 27
2

If using getApplicationContext() as the parameter while inflating the layout, you can try to use getBaseContext() instead. e.g.

    View.inflate(getBaseContext(),
            getLayoutId() == 0 ? R.layout.page_default : getLayoutId(),
            null);
user1744585
  • 137
  • 1
  • 1
  • 10
2

In your app/build.gradle add this dependency:

implementation "com.google.android.material:material:1.1.0-alpha03"

Update your styles.xml AppTheme's parent:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar"/>
Mark Pazon
  • 5,962
  • 2
  • 31
  • 48
1

NOTE: I had intended this as an answer, but further testing reveals it still fails when built using maven from the command line, so I've had to edit it to be a problem! :-(

In my case when I got this error I was already using a AppCompat Theme and the error didn't make much sense.

I was in the process of mavenizing my android build. I had already dependencies on the apklib and jar versions of app compat, thus:

    <!-- See https://github.com/mosabua/maven-android-sdk-deployer -->
        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v7-appcompat</artifactId>
            <version>${compatibility.version}</version>
            <type>apklib</type>
        </dependency>

        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v7-appcompat</artifactId>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v7</artifactId>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>android.support</groupId>
            <artifactId>compatibility-v4</artifactId>
        </dependency>

Now, when I import the maven project and build and run from IntelliJ it's fine.

But when I build and deploy and run from the command line with maven I still get this exception.

Andrew Mackenzie
  • 5,005
  • 4
  • 42
  • 61
1

Change Theme from highlighted tab in picture.enter image description here

Saleem Kalro
  • 882
  • 8
  • 11
1

In my case, I was using a style called "FullScreenTheme", and although it seemed to be correctly defined (it was a descendant of Theme.AppCompat) it was not working.

I finally realized that I was using an AAR library that internally also had defined a style called "FullScreenTheme" and it was not descendant of Theme.AppCompat. The clashing of the names was causing the problem.

Fix it by renaming my own style name so now Android is using the correct style.

tomacco
  • 679
  • 4
  • 25
1

In my case, I had AppTheme in AndroidManifest set correctly to a style that inherited from Theme.AppCompat. However, the individual activities had style settings in AndroidManifest that were overriding that.

arlomedia
  • 7,625
  • 5
  • 53
  • 96
1

Do not forget to clean the project after VCS Local History restore

Umer Waqas
  • 513
  • 4
  • 12
1

First of all, add this as import => import androidx.appcompat.app.AlertDialog

I am posting this being the smallest ever solution to the problem. I just changed the instantiation of

new AlertDialog.Builder(mContex)

to

new AlertDialog.Builder(mContext, R.style.PreferenceDialogLight)

Where <style name="PreferenceDialogLight" parent="Base.Theme.MaterialComponents.Dialog.Alert">

SaadurRehman
  • 274
  • 2
  • 14
-1

For me, the Android SDK didn't seem to be able to find the styles definition. Everything was wired correctly and doing a simple project clean fixed it for me.

Joe Plante
  • 5,952
  • 2
  • 27
  • 23
-1

just make that

getApplicationContext().getTheme().applyStyle(R.style.Theme_Mc, true);

and In your values/styles.xml add this

 <style  name="Theme.Mc" parent="Theme.AppCompat.Light.NoActionBar">
         <!-- ADD Your Styles  -->


     </style>
Mourad MAMASSI
  • 717
  • 10
  • 13
-1

Instead of all of this, about changing a lot of this in your app.. just do it simple as this video does.

https://www.youtube.com/watch?v=Bsm-BlXo2SI

I already use it so... it's a 100 percent effective.

Bryan J. Diaz
  • 336
  • 2
  • 8
-3

In case anybody still wondering about this issue.

try this :

new android.support.v7.app.AlertDialog.Builder(this)
Wai Ha Lee
  • 7,664
  • 52
  • 54
  • 80
Mansoor Cool
  • 31
  • 1
  • 1
  • 2
    That's not related to the question. – Raptor Apr 12 '16 at 08:09
  • To [reviewers](http://stackoverflow.com/review/low-quality-posts/11985108): if the answer is bad, even if it's not relevant to the question, but is an attempt to answer the question (like this appears to be), don't recommend deletion: downvote! See [You're doing it wrong: A plea for sanity in the Low Quality Posts queue](http://meta.stackoverflow.com/q/287563/1364007). This is an answer. You may not agree with it, but it is an attempt to answer the question. – Wai Ha Lee Apr 12 '16 at 16:30
-3

For my Xamarin Android project (in MainActivity.cs), I changed…

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity

to

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity

…and the error went away. I realise that isn't a solution for everyone but it might give a clue to the underlying problem.

Andrew Jens
  • 975
  • 14
  • 16