Search code examples
androidpreferenceactivity

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


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()


Solution

  • 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);
            }
        }
    
    }