I want to show an ActionBar in my Activity while only showing a closing symbol. Therefore I used the method getSupportActionBar():
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle("Add Event");
But it throws a NullPointerExeption because apparently there's no ActionBar to call:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tutorial/com.example.tutorial.AddEventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setHomeAsUpIndicator(int)' on a null object reference
In my MainActivity I implemented a Drawer Navigation where I already used a toolbar that works:
public class MainActivity extends AppCompatActivity {
protected DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
// Make sure to be using androidx.appcompat.app.ActionBarDrawerToggle version.
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// This will display an Up icon (<-), we will replace it with hamburger later
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Setup toggle to display hamburger icon with nice animation
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
How do I fix that?
Thanks in advance!
Replace this line :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
with this line :
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
This should solve your problem.
You may try to add following attribute to your MainActivity item under your ActivityManifest.xml
android:theme="#style/Theme.AppCompat.Light.DarkActionBar"
Then try to access it with the getSupportActionBar(). With this way you can choose the activities that you don't or do want to include actionbars by using relevant themes. For example:
<activity
android:name=".SecondActivity"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar"
android:parentActivityName=".MainActivity" />
I cannot hide the title's view from an Activity that I'm styling as a Dialog.
android:windowNoTitle is set to false in the reference style, and RequestWindowFeature(WindowFeatures.NoTitle) is called from OnCreate.
Is there another setting for completely removing the title's view from an Activity?
styles.xml
<style name="Theme.AppCompat.Light.Dialog_Configuration" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowNoTitle">true</item>
<item name="android:windowCloseOnTouchOutside">false</item>
</style>
ConfigurationView
[Activity(
Label = "Configuration",
MainLauncher = false,
Theme = "#style/Theme.AppCompat.Light.Dialog_Configuration",
ExcludeFromRecents = true
)]
public class ConfigurationView : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
RequestWindowFeature(WindowFeatures.NoTitle);
SetContentView(Resource.Layout.Configuration);
}
}
Are you using toolbar? You can try this
getSupportActionBar().setDisplayShowTitleEnabled(false);
or
requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title.
getSupportActionBar().hide(); //hide the title bar.
While you have removed the title, you also need to remove the title bar as well. Try adding the following line to your onCreate method:
getSupportActionBar().hide();
Write this in the OnCreate method just after SetContentView:
ActionBar.Hide();
Alternatively, you could try this
NavigationPage.SetHasNavigationBar(this, false);
I have a generic
MyActivity extends AppCompatActivity
I don't override the toolbar with a custom xml defined toolbar, just use the generated one Android provides.
I can set the title via your normal
getSupportActionBar().setTitle("foo");
but setting the subtitle via
getSupportActionBar().setSubtitle("bar");
doesn't set it. It remains blank. I'm doing this onCreate()
(I feel I've done this many times before with no fail)
Although I've noticed if I visit another activity, then return, the subtitle would then show... not on orientation change, not on recreate() but only when I'm returning from an activity.
I'm experiencing this on 5.0 and 7.0
For the time being I'll likely define my own Toolbar and move forward since that seems where most people have solutions for this same problem.
Relevant code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_replenishment_list);
ButterKnife.bind(this);
MyApplication.getInstance().getComponent().inject(this);
setupUI();
}
private void setupUI() {
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
//TODO: not working unless activity is recreated...
// explore custom xml defined toolbar
//actionBar.setTitle("different title than what is defined in manifest"); <-- this does work, but not this
actionBar.setSubtitle(UserUtil.getFormattedFirstNameLastName(userService.getUserFromJWT(), this));
}
}
I have put the below code in my onCreate() method.
ActionBar actionBar = getActionBar();
if (actionBar==null) {
System.out.println("TEST NULL");
} else {
System.out.println("TEST NOT NULL");
}
The result is null. When I add the toolbar first it works fine.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getActionBar();
actionBar.setSubtitle("TESTING");
Your getSupportActionBar or getActionBar will return null if you didn't set toolbar to it. You need to set the toolbar to your action bar before using getSupportActionBar or getActionBar.
In my app, I have back button as default on toolbar after the splash screen.(i.e) on home page. I don't need any icon or title on my home page toolbar alone.
How can I hide the button on home screen?
If I disable back button on MainActivity by
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
It shows NullPointerException
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
HomeFragment homeFragment = new HomeFragment();
showFragment(homeFragment, Constants.HOME_FRAGMENT, false);
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
showAlertDialog(Constants.EXIT_APP, Constants.APP_NAME);
} else {
getFragmentManager().popBackStackImmediate();
}
}
public void showFragment(Fragment fragment, String back_stack_name, boolean isAddToBackStack) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment);
if (isAddToBackStack) {
transaction.addToBackStack(back_stack_name);
}
transaction.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int vid = item.getItemId();
switch (vid) {
case android.R.id.home:
this.onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I found the answer for my question.
In fragments:
For title without back arrow
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
For Title with back arrow
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowCustomEnabled(false);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
In activity:
For title without back arrow
getSupportActionBar().setDisplayShowCustomEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setTitle(title);
For Title with back arrow
getSupportActionBar().setDisplayShowCustomEnabled(false); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(title);
For colored back button, modify in style
<style name="ToolbarColoredBackArrow" parent="AppTheme">
<item name="android:textColorSecondary">#ffffff</item> <!-- white arrow -->
</style>
Use theme in toolbar
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
app:theme="#style/ToolbarColoredBackArrow"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
Possible reason:
1) you dont have the support actionbar.
2) you might be hide the supportActionBar using styles.
3) you are hiding it programatically in your activity.
solution:
If you are using toolbar in activty , try using this below code in your onCreate() method:
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
I am using a toolbar as my actionbar in an activity. I am trying to add the method getActionBar().setDisplayHomeAsUpEnabled(true); to the Activity.java file for Up navigation for older devices.
The method produces the following error message in Android Studio:
Method invocation may produce java.lang.NullPointerException
The Up navigation on the toolbar works fine on newer devices...now I'm trying to figure out how to make sure it will work for older devices.
Please advise.
From build.gradle:
dependencies {
compile "com.android.support:appcompat-v7:22.1.0"
}
From AndroidManifest.xml:
android:theme="#style/Theme.AppCompat.NoActionBar.FullScreen"
From styles.xml
<style name="Theme.AppCompat.NoActionBar.FullScreen" parent="AppTheme">
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>
from Activity.java
public class CardViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cardviewinput);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
// Up navigation to the parent activity for 4.0 and earlier
getActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationIcon(R.drawable.ic_action_previous_item);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
Actually Android Studio isn't showing you an "error message", it's just a warning.
Some answers propose the use of an assertion, Dalvik runtime has assertion turned off by default, so you have to actually turn it on for it to actually do something. In this case (assertion is turned off), what you're essentially doing is just tricking Android Studio to not show you the warning. Also, I prefer not to use "assert" in production code.
In my opinion, what you should do is very simple.
if(getActionBar() != null){
getActionBar().setDisplayHomeAsUpEnabled(true);
}
Update:
In case you're using the support library version of the Action Bar, you should replace getActionBar() with getSupportActionBar().
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
First off, you need to set the toolbar as the support ActionBar.
Then if you're certain it's going to be there all the time, just assert it as != null. This will tell the compiler it won't be null, so the null check passes.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.cardviewinput);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // it's getSupportActionBar() if you're using AppCompatActivity, not getActionBar()
}
Thank You Andrew for your answer.
If you have a Nav Drawer or something else that uses getSupportActionBar() you need to add assert getSupportActionBar() != null;
Peace,
Example:
#Override
public void setTitle(CharSequence title) {
mTitle = title;
assert getSupportActionBar() != null;
getSupportActionBar().setTitle(mTitle);
}
Try this :
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
What I have done is override the getSupportActionBar() method in my base Activity and add a #NonNull annotation. This way, I only get one lint warning in the base activity about how I use #NonNull annotation for something that has a #Nullable annotation.
#NonNull
#Override
public ActionBar getSupportActionBar() {
// Small hack here so that Lint does not warn me in every single activity about null
// action bar
return super.getSupportActionBar();
}
I created a generic class such as:
public final class Cast
{
private Cast() {}
/**
* Helps to eliminate annoying NullPointerException lint warning.
*/
#android.support.annotation.NonNull
public static <T> T neverNull(T value)
{
return value;
}
}
then I can use it for any call with NullPointerException warning for which I am sure that it will never happen, e.g.
final ActionBar actionBar = Cast.neverNull(getSupportActionBar());
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
P.S. don't forget to add "com.android.support:support-annotations" to your gradle file.
add assert getSupportActionBar() != null; before getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if(actionBar != null) {
actionBar.setHomeButtonEnabled(true);
actionBar.setBackgroundDrawable(ContextCompat.getDrawable(mContext,
R.drawable.action_bar_gradient));
}
use this theme: android:theme="#style/Theme.AppCompat.Light.NoActionBar"
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Title");
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_action_previous_item);
actionBar.setDisplayHomeAsUpEnabled(true);
Alternatively you could assert actionbar to not null.Add the assertion before calling your actionbar as follows
assert getSupportActionBar() != null;
Final snippet would therefore look as follows:
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Try this :
setSupportActionBar (toolbar);
if(getSupportActionBar () != null) {
assert getSupportActionBar () != null;
getSupportActionBar ().setDisplayHomeUpEnabled(true);
}
Note that setSupportActionBar(toolbar) should be before getSupportActionBar().
if(getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
OR
Replace the MainActivity extends AppCompatActivity to public class MainActivity extends AppCompatActivity
just check getSupportActionBar not equal to null
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Daily Shopping List");
}
If you are importing
android.app.ActionBar
you have to use getActionBar()
and if you are importing
android.support.v7.app.ActionBar
use getSupportActionBar()