Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getActionBar() returns null in PreferenceActivity (AppCompat-v7 21)

Tags:

I have implemented DoneBar (two buttons in actionbar) in PreferenceActivity as provided in v20 sdk samples, but after updating SDK and AppCompat to version 21 my app crashes at

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayOptions(int, int)' on a null object reference

That is because getActionBar() returns null. And There is no getSupportActionBar() as in ActionBarActivity.

So my question is how to get that actionbar object in PreferenceActivity so I could apply custom view on it?

SOLVED

After some research I managed to solve this problem by using PreferenceFragment with ActionBarActivity so I could call getSupportActionBar()

like image 869
Olegas Gončarovas Avatar asked Oct 18 '14 11:10

Olegas Gončarovas


2 Answers

I managed to fix this issue by specifying custom theme for my settings activity,

<style name="SettingsTheme" parent="style/Theme.AppCompat.Light">
    <item name="android:windowNoTitle">false</item>
    <item name="android:windowActionBar">true</item>
</style>

and : android:theme="@style/SettingsTheme" in manifest for activity

actionbar is again showing on KITKAT and LOLIPOP and (have not tested it) back to api v11. I tested it and it works (with no actionbar as expected) on api 10.

From debugging on lolipop, FEATURE_NO_TITLE was being set in PhoneWindow.java:3243 :

   if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
        requestFeature(FEATURE_NO_TITLE);

which removes FEATURE_ACTION_BAR

[edit]

but this action bar is not from material theme, so still its not perfect

[edit2]

I gave up with Headers, now I am using PreferenceFragment backport from github. Now all my actionbars are the same after upgrade to appcompact 21.

like image 71
marcinj Avatar answered Oct 02 '22 15:10

marcinj


as xXx requested I am providing example how I done:

public class SettingsActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Display the fragment as the main content.
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();

        // use action bar here
        ActionBar actionBar = getSupportActionBar();
    }

    public static class SettingsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle paramBundle) {
            super.onCreate(paramBundle);
            addPreferencesFromResource(R.xml.pref_settings);
        }
    }

}
like image 38
Olegas Gončarovas Avatar answered Oct 02 '22 16:10

Olegas Gončarovas