'AppCompatDelegete returns null ActionBar

AppCompatDelegate returns null when calling getSupportActionBAr() this is the function I use to set the actionbar

public void setSupportActionBar(@NonNull Toolbar toolbar) {
    getDelegate().setSupportActionBar(toolbar);
    if (getDelegate().getSupportActionBar() != null)
        getDelegate().getSupportActionBar().setDisplayHomeAsUpEnabled(true);

}

I am passing a NonNull Toolbar and on the first line, it is set as the supportActoinBar. Then in the next line, it is giving null for getSupportActionBar() why it is returning null. it was working until this afternoon and I inflated menus on the support actionbar and all of a sudden it is giving null.



Solution 1:[1]

I was having the same issue and my problem was calling onCreate on the AppCompatDelegate instance after calling super.onCreate. AppCompatDelegate.onCreate must be called before super.onCreate. reference

Example:

protected void onCreate(Bundle savedInstanceState) {
    getDelegate().onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    // ...
}

Solution 2:[2]

I know this is super old, but it does come up and still has no answer and the documentation for this is still not good enough. This is especially true for the documentation of AppCompatDialog.getSupportActionBar() which suggests that you can have an action bar in the dialog.

However getDelegate().setSupportActionBar(toolbar) will work only within an AppCompatActivity. It will not work for AppCompatDialog, because in AppCompatDelegateImpl.setSupportActionBar we find this:

if (!(mHost instanceof Activity)) {
   // Only Activities support custom Action Bars
       return;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanlok Lee
Solution 2 M.Paunov