getActionBar() == null When it Shouldn't - android

I feel like I must be missing something crazy. I am converting my code written to work with ABS (and it did work), and switching it to use the native ActionBar. I set the min SDK to 14 and switched things out for the framework versions, now I can't get the ActionBar to exist.
My Activity:
public class HomeActivity extends Activity {
#Override
protected void onCreate(#CheckForNull Bundle icicle) {
super.onCreate(icicle);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
}
}
My AndroidManifest:
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17"/>
...
<activity android:launchMode="singleTop" android:name=".ui.HomeActivity" android:theme="#android:style/Theme.Holo">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="target device" android:value="universal"/>
</activity>
My Robolectric Test:
#RunWith(RobolectricTestRunner.class)
public class HomeActivityTest {
#Test
public void testActionBarDisplay() {
// Given
final HomeActivity activity_under_testing = new HomeActivity();
// When
activity_under_testing.onCreate(null);
// Then
assertThat(activity_under_testing.getActionBar())
.hasDisplayOptions(ActionBar.DISPLAY_SHOW_HOME
|ActionBar.DISPLAY_SHOW_TITLE
|ActionBar.DISPLAY_USE_LOGO);
}
}
I'm using FEST-Android for the assertThat (couldn't possibly be the issue).
The issue:
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 7.563 sec <<< FAILURE!
testActionBarDisplay(com.imminentmeals.android.base.ui.HomeActivityTest) Time elapsed: 6.588 sec <<< FAILURE!
java.lang.AssertionError: expecting actual not to be null
at com.imminentmeals.android.base.ui.HomeActivityTest.testActionBarDisplay(HomeActivityTest.java:28)
I should add that I'm using Robolectric 2.0 Alpha 2. I skipped the test, and packaged my apk, and the ActionBar seems to work fine, so I'm feeling like this must be a Robolectric issue? But I thought it should work fine with native Android since it was running native Android code.

This question is rather old but I will post my solution in case someone faces the same problem.
I was facing the same problem as Dandre, where I was using Robolectric 2.3, minSDK 16, and using the native ActonBar and yet getActionBar() kept returnign null. The solution was to ensure my style was referring to a theme which explicitly mentions ActionBar. In my case,I was using Theme.Light. By changing the theme to Theme.Holo.Light.DarkActionBar, I got it to work. I believe Dandre had the same issue, given that his theme was Theme.Holo.
I find it weird that the theme was the cause of the problem, given that it does not affect my app. Maybe someone can explain why?

if you use ActionBarDrawerToggle
put getActionBar() inside of onDrawerOpened(View drawerView){}
public void onDrawerOpened(View drawerView) {
title = getActionBar().getTitle();
getActionBar().setTitle("Open Drawer");
}

Extend ActionBarActivity in place of FragmentActivity.
ActionBarActivity internally extends FragmentActivity, so no need to worry.
Use android.support.v7 type ActionBar Activity.
import android.support.v7.app.ActionBarActivity;
Use getSupportActionBar() in place of getActionBar()
Check in your Manifest file, if NoTitleBar theme is used then remove that line
android:theme="#android:style/Theme.NoTitleBar" // remove this line
If still problem is not resolved then use FEATURE_ACTION_BAR above the setContentView() method.
requestWindowFeature(Window.FEATURE_ACTION_BAR);

In your Manifest you should make the theme Theme.Sherlock instead of Theme.Holo.
You need to extend SherlockActivity or SherlockFragmentActivity.
To return the ActionBar call getSupportActionBar when you're using ABS.
Also, you don't need to call Window.FEATURE_ACTION_BAR. Using the Holo theme is enough.
From the ActionBarSherlock docs
Action Bar API
When creating an activity to use the action bar on all versions of
Android, you must declare your activity to extend any of the activity
classes that start with 'Sherlock' (e.g., SherlockActivity,
SherlockFragmentActivity). Interaction with the action bar is handled
by calling getSupportActionBar() (instead of getActionBar()).
You can read the docs here
You can read more about styling ABS here

Related

Rendering problems when choosing Holo Light theme [duplicate]

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?
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.
All you need to do is add android:theme="#style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.
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.
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);
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/
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!
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.
go to your styles and put the parent
parent="Theme.AppCompat"
instead of
parent="#android:style/Theme.Holo.Light"
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" />
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>
Just Do
new AlertDialog.Builder(this)
Instead of
new AlertDialog.Builder(getApplicationContext())
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"
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.
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>
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>
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,....);
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">
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);
}
Make sure you are using an activity context while creating a new Alert Dialog and not an application or base context.
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?
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.
In case the AndroidX SplashScreen library brought you here ...
This is because Theme.SplashScreen also has no R.styleable.AppCompatTheme_windowActionBar:
if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) {
a.recycle();
throw new IllegalStateException(
"You need to use a Theme.AppCompat theme (or descendant) with this activity.");
}
This requires switching the theme to the postSplashScreenTheme, before calling super():
#Override
protected void onCreate(Bundle savedInstanceState) {
/* When switching the theme to dark mode. */
if (savedInstanceState != null) {
this.setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
/* When starting the Activity. */
if (savedInstanceState == null) {
SplashScreen.installSplashScreen(this);
}
}
Then the Theme.SplashScreen from AndroidManifest.xml won't interfere.
Also quite related: When using Theme.MaterialComponents, there's a bridge theme contained, which works as substitute for Theme.AppCompat: Theme.MaterialComponents.DayNight.NoActionBar.Bridge.
This Bridge theme works despite Theme.MaterialComponents not inherits from Theme.AppCompat:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge" />
<style name="AppTheme.SplashScreen" parent="Theme.SplashScreen" />
</resources>
You have many solutions to that error.
You should use Activity or FragmentActivity instead of ActionbarActivity or AppCompatActivity
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.
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>
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.
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.
I have faced same problem.
If you are providing context to any class or method then provide YourActivityName.this instead of getApplicationContext().
Do this
builder = new AlertDialog.Builder(YourActivity.this);
Instead of
builder = new AlertDialog.Builder(getApplicationContext());
Change your theme style parent to
parent="Theme.AppCompat"
This worked for me ...
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>
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"

AutoCompleteTextView : Drop down ListView background is black [duplicate]

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?
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.
All you need to do is add android:theme="#style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.
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.
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);
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/
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!
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.
go to your styles and put the parent
parent="Theme.AppCompat"
instead of
parent="#android:style/Theme.Holo.Light"
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" />
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>
Just Do
new AlertDialog.Builder(this)
Instead of
new AlertDialog.Builder(getApplicationContext())
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"
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.
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>
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>
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,....);
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">
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);
}
Make sure you are using an activity context while creating a new Alert Dialog and not an application or base context.
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?
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.
In case the AndroidX SplashScreen library brought you here ...
This is because Theme.SplashScreen also has no R.styleable.AppCompatTheme_windowActionBar:
if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) {
a.recycle();
throw new IllegalStateException(
"You need to use a Theme.AppCompat theme (or descendant) with this activity.");
}
This requires switching the theme to the postSplashScreenTheme, before calling super():
#Override
protected void onCreate(Bundle savedInstanceState) {
/* When switching the theme to dark mode. */
if (savedInstanceState != null) {
this.setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
/* When starting the Activity. */
if (savedInstanceState == null) {
SplashScreen.installSplashScreen(this);
}
}
Then the Theme.SplashScreen from AndroidManifest.xml won't interfere.
Also quite related: When using Theme.MaterialComponents, there's a bridge theme contained, which works as substitute for Theme.AppCompat: Theme.MaterialComponents.DayNight.NoActionBar.Bridge.
This Bridge theme works despite Theme.MaterialComponents not inherits from Theme.AppCompat:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge" />
<style name="AppTheme.SplashScreen" parent="Theme.SplashScreen" />
</resources>
You have many solutions to that error.
You should use Activity or FragmentActivity instead of ActionbarActivity or AppCompatActivity
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.
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>
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.
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.
I have faced same problem.
If you are providing context to any class or method then provide YourActivityName.this instead of getApplicationContext().
Do this
builder = new AlertDialog.Builder(YourActivity.this);
Instead of
builder = new AlertDialog.Builder(getApplicationContext());
Change your theme style parent to
parent="Theme.AppCompat"
This worked for me ...
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>
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"

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

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?
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.
All you need to do is add android:theme="#style/Theme.AppCompat.Light" to your application tag in the AndroidManifest.xml file.
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.
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);
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/
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!
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.
go to your styles and put the parent
parent="Theme.AppCompat"
instead of
parent="#android:style/Theme.Holo.Light"
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" />
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>
Just Do
new AlertDialog.Builder(this)
Instead of
new AlertDialog.Builder(getApplicationContext())
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"
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.
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>
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>
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,....);
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">
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);
}
Make sure you are using an activity context while creating a new Alert Dialog and not an application or base context.
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?
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.
In case the AndroidX SplashScreen library brought you here ...
This is because Theme.SplashScreen also has no R.styleable.AppCompatTheme_windowActionBar:
if (!a.hasValue(R.styleable.AppCompatTheme_windowActionBar)) {
a.recycle();
throw new IllegalStateException(
"You need to use a Theme.AppCompat theme (or descendant) with this activity.");
}
This requires switching the theme to the postSplashScreenTheme, before calling super():
#Override
protected void onCreate(Bundle savedInstanceState) {
/* When switching the theme to dark mode. */
if (savedInstanceState != null) {
this.setTheme(R.style.AppTheme);
}
super.onCreate(savedInstanceState);
/* When starting the Activity. */
if (savedInstanceState == null) {
SplashScreen.installSplashScreen(this);
}
}
Then the Theme.SplashScreen from AndroidManifest.xml won't interfere.
Also quite related: When using Theme.MaterialComponents, there's a bridge theme contained, which works as substitute for Theme.AppCompat: Theme.MaterialComponents.DayNight.NoActionBar.Bridge.
This Bridge theme works despite Theme.MaterialComponents not inherits from Theme.AppCompat:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge" />
<style name="AppTheme.SplashScreen" parent="Theme.SplashScreen" />
</resources>
You have many solutions to that error.
You should use Activity or FragmentActivity instead of ActionbarActivity or AppCompatActivity
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.
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>
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.
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.
I have faced same problem.
If you are providing context to any class or method then provide YourActivityName.this instead of getApplicationContext().
Do this
builder = new AlertDialog.Builder(YourActivity.this);
Instead of
builder = new AlertDialog.Builder(getApplicationContext());
Change your theme style parent to
parent="Theme.AppCompat"
This worked for me ...
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>
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"

ActionBarSherlock dialog is not transparent and not dark

I am using ActionBarSherlock (ABS) and would like to add a dialog to my application as one can see in the ABS Demos Sample application provided by the project. The dialog sample look like this:
I created an activity myself. Here is relevant source code:
public class Dialog extends SherlockActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Sherlock___Theme_DarkActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
}
For some reason, Android forces me to add setTheme() although the ABS sample does not do this. If I leave it out, I will run into the following error.
java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.
My AndroidManifest.xml has the following settings, which are very similar to the ones from the ABS sample.
<activity
android:name=".activities.Dialog"
android:label="#string/title_activity_dialog"
android:theme="#style/Theme.Sherlock.Dialog" >
</activity>
The following screenshot shows how my dialog activity looks like.
I am using ActionBarSherlock 4.1.0 with maps support, the Android Support library v4.
Question: Can you figure out, why it looks so different?
Dark vs. light user interface
Transparent vs. opaque background
With and without actionbar
Update:
The ABS sample starts the dialog activity as follows:
protected void onListItemClick(ListView l, View v, int position, long id) {
Map<String, Object> map = (Map<String, Object>)l.getItemAtPosition(position);
Intent intent = (Intent) map.get("intent");
startActivity(intent);
}
I start the dialog activity as follows:
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(R.string.title_menuItemDialogActivtiy)
.setIcon(R.drawable.ic_action_dialog)
.setIntent(new Intent(this, Dialog.class))
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
Meanwhile, I saw that this pattern is deprecated. Instead, I could use a DialogFragment. The question that occurs here: How can I integrate the fragment with the action menu item?
Alternative solution:
I decided to use a DialogFragment instead of an Activity as I estimate it to be more "future-safe". I basically followed the very informative tutorial Using DialogFragments (posted June 3, 2012), which I like to recommend as perfect starting point for any interest reader. Further, I like to add related and useful posts:
Validating user input
Softkeyboard vs. separate DONE button
The output you are seeing definitely comes from setting the Theme in Java code (which will override the value set in XML). I just stood up the following sample application (this is literally all there is) and replicated the issue by adding the extra setTheme() call.
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".Dialog"
android:theme="#style/Theme.Sherlock.Dialog">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
And the Dialog...
public class Dialog extends SherlockActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
text.setText("This is a dialog!");
setContentView(text);
}
}
Now as to why you got an exception without that extra method, that's another matter (and quite strange). As you can see it should work with as little code as I provided above.
Perhaps make sure that both the library project and your project are being compiled with at least Android 4.0 (API 14) as this is a requirement of the library.
Beyond that, if you just want to show a Dialog in your application, does it need to be a themed Activity? This is not common. You can always create a simple Dialog or AlertDialog subclass to display as well. Take a look here for more information...
Try setting a theme for the application.
<application
android:theme="#style/Theme.Sherlock"
The dialogue should inherit the theme. If you've already set that then remove the android:theme tag in the activity declaration and the setTheme() call and see what happens. The reason you get the error without setTheme is because SherlockActivities must have one of the themes in the error message and you had it set to something else in the manifest setTheme() overrode this before you got into trouble.

getActionBar() returns null

I'm having an odd problem.
I am making an app with targetsdk 13.
In my main activity's onCreate method i call getActionBar() to setup my actionbar. This works fine when running on the Android 3.2 emulator, but when using Android 3.0 and 3.1 the getActionBar() method returns null.
I find this extremely odd, and i cannot see any reason why it would do so.
Is this a bug with the emulators or is there something i need to do, in order to ensure that my application has an actionbar?
SOLUTION:
I think I've found a solution for this problem.
I wasn't using the setContentView to set a layout for the activity. Instead I was using fragmentTransaction.add(android.R.id.content, mFragment, mTag) to add a fragment to the activity.
This worked fine in 3.2, but in earlier honeycomb versions the action bar is apparently not set if you don't use the setContentView in the onCreate() method.
So I fixed it by using the setContentView() method in my onCreate() method and just supplying it with a layout that contained an empty FrameLayout.
I can still use the fragmentTransaction.add(android.R.id.content, mFragment, mTag) method the same way as before.
It's not the prettiest fix, but it works.
Can use getSupportActionBar() instead of getActionBar() method.
If you are using the support library
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
use getSupportActionBar() instead of getActionBar()
* Update:
The class ActionBarActivity now is deprecated:
import android.support.v7.app.ActionBarActivity;
I recommend to use:
import android.support.v7.app.AppCompatActivity
if you are using android.support.v7.app.AppCompatActivity
public class HomeActivity extends AppCompatActivity {
Then you should be using android.support.v7.app.ActionBar
ActionBar ab = getSupportActionBar();
If you are using android.support.v4.app.FragmentActivity
public class HomeActivity extends FragmentActivity {
then you should be using android.app.ActionBar
ActionBar ab = getActionBar();
If you are using android.support.v7.app.ActionBarActivity
public class HomeActivity extends ActionBarActivity {
you should be using android.support.v7.app.ActionBar
ActionBar ab = getSupportActionBar();
You have to define window type as actionbar before activity render its view.
use
requestWindowFeature(Window.FEATURE_ACTION_BAR);
before calling setContentView() method.
I faced the above issue where getActionBar() method returns null. I was calling the getActionBar() after setting the setContentView() and still its returning a null.
I resolved the issue by setting the min-sdk version in Android Manifest file that was missing initially.
<uses-sdk android:minSdkVersion="11" />
ActionBar needs application or activity's Theme to have an app title. Make sure you have not styled your application or activity as Theme.NOTITLE.
<application
android:name="com.xxx.yyy"
android:debuggable="false"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/Theme.NoTitle"> // remove this line if you have this in your code
<activity
android:name="com.xxx.yyy.Activity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="#style/Theme.NoTitle" // remove this line if you have in your code
android:windowSoftInputMode="adjustResize|stateHidden" >
import android.support.v7.app.AppCompatActivity;
then
extends AppCompatActivity
then use
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
This answer is late but might be helpful to anyone who arrives from Google: You might well need to declare
<item name="android:windowActionBar">true</item>
in your styles.xml. It seems false can be the default. You also need to be on API 11 or higher.
More details can be found in the documentation here. Specifically, quote:
Tip: If you have a custom activity theme in which you'd like to remove
the action bar, set the android:windowActionBar style property to
false. However, if you remove the action bar using a theme, then the
window will not allow the action bar at all, so you cannot add it
later—calling getActionBar() will return null.
I had the same problem and one of the solutions was to use setContentView() before calling getActionBar().
But there was another thing that fixed the problem. I specified theme for the application to be #android:style/Theme.Holo.Light.
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light" >
...
</application>
I think any theme, which has <item name="android:windowActionBar">true</item> in it, can be used.
The main reason for that is using themes that are not supporting ActionBar:
In manifest file add the following either in your target activity or application element (if you want to unify the theme over whole application)
Examples of themes that are supporting action bar "Theme.AppCompat.Light" or "Theme.Holo.Light" ...
android:theme="#android:style/Theme.Holo.Light"
It is better to put all styles in styles.xml and use it everywhere using "#style/themName" so the previous one will be
android:theme="#style/AppTheme"
and styles.xml will have the following:
<style name="AppTheme" parent="Theme.AppCompat.Light">
Hints:
There is some themes that can not be used in old SDKs like "#android:style/Theme.Holo.Light.DarkActionBar" is not supported before SDKs version 14.
To allow your app to support minimum specific version of SDK you could add the following under <app> element:
<uses-sdk android:minSdkVersion="14" />
To specify min SDK version in AndroidStudio, you could by using app's Gradle file.
android{
defaultConfig{
minSdkVersion 14
targetSdkVersion 21
}
}
I ran into this problem . I was checking for version number and enabling the action bar only if it is greater or equal to Honeycomb , but it was returning null. I found the reason
and root cause was that I had disabled the Holo Theme style in style.xml under values-v11 folder.
go to the AndroidManifest.xml and replace
android:theme="#style/AppTheme"
by
android:theme="#android:style/Theme.Holo.Light.DarkActionBar"
Use getSupportActionBar() instead of getActionBar()
In my case, I had this in my code which did not work:
#Override
protected void onCreate(Bundle savedInstanceState) {
context = getApplicationContext();
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then I played with the order of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
}
And it worked!
Conclusion: requestWindowFeature should be the first thing you call in the onCreate method.
I had the same issue. It solved by chaning App theme in styles.xml
Before
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
After
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
One thing I wanted to add since I just ran into this, if you are trying to getActionBar() on an Activity that has a parent, it will return null. I am trying to refactor code where my Activity is contained inside an ActivityGroup, and it took a good few minutes for me to go "oh duh" after looking at the source of how an ActionBar gets created in source.
I solve it by this changes:
change in minifest android:theme="#android:style/Theme.Holo.Light" >
add to class extends ActionBarActivity
add import to class import android.support.v7.app.ActionBarActivity
To add to the other answers:
Make sure you call setActionBar() or setSupportActionBar() in your onCreate() method before calling the getActionBar():
Define some Toolbar in your activity.xml, then in the onCreate():
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
// Now you can use the get methods:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
In my case I simply had to extend AppCompatActivity instead of Activity
supportActionBar?.setDisplayHomeAsUpEnabled(true)
Full activity example class:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
//class LocationFound : Activity() { <-----Does not seem to work with ActionBar in recent versions
class LocationFound : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_location_found)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
} }
On Versions
minSdkVersion 22
targetSdkVersion 29
I know I am late to the party (and new to Android) on this question but I found the information here very helpful and thought I should add the findings of my own endeavours with getting ActionBar to work as I wanted in case others like me come looking for help.
I have a widget which is a floating window with no window title. I use a style theme to implement android:windowIsFloating, android:backgroundDimEnabled and android:windowNoTitle. The widget worked fine until I wanted to add a button that called a fragment pager with several list fragment pages and used the ActionBar. It would crash on the pager activity with a null pointer exception. I narrowed it down to the ActionBar being null. Following the findings of previous people who contributed to this thread I removed my theme from the manifest file and the ActionBar worked fine but now my window now longer floated (it was fullscreen) and it had a page title I did not want.
Further research took me to the Styles and Themes API Training Guide which led me to a solution. I discovered I could add my custom theme to individual activities in the manifest file whereas before I was applying it to the application. All my windows now have the desired appearance.
Try extending your Activity class from ActionBarActivity. This solved it for me. Do something like the following:
public class MyActivity extends ActionBarActivity
{
. . .
In my case the class was extending only from Activity.
This may also help some people.
In my case, it was because I had not defined a context in the menu.xml
Try this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.ActionBarActivity">
Instead of this:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
Just check the implementation of source code by command click:
private void initWindowDecorActionBar() {
Window window = getWindow();
// Initializing the window decor can change window feature flags.
// Make sure that we have the correct set before performing the test below.
window.getDecorView();
if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
return;
}
mActionBar = new WindowDecorActionBar(this);
mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
mWindow.setDefaultIcon(mActivityInfo.getIconResource());
mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
}
requestWindowFeature(Window.FEATURE_ACTION_BAR); Fixed my issue as I saw requestWindowFeature(Window.FEATURE_ACTION_BAR) is failing; code is open source use it !!
android.support.v7.app.ActionBar actionBar = getSupportActionBar();
works pretty quickly
If calling this method from Fragment the make sure to call this in onActivityCreated()

Categories

Resources