0

I have some questions about a discussed topic.

I get a NullPointerException from the following code. My questions are:

  1. Why do I get a NullPointerException ? i.e. why does getActionBar() return null ?

Request answers to be in Layman terms please.

SettingActivity.java

public class SettingsActivity extends PreferenceActivity {
/**
 * Determines whether to always show the simplified settings UI, where
 * settings are presented in a single list. When false, settings are shown
 * as a master/detail two-pane view on tablets. When true, a single pane is
 * shown on tablets.
 */
private static final boolean ALWAYS_SIMPLE_PREFS = false;

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

    setupActionBar();
}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        // Show the Up button in the action bar.
        getSupportActionBar()
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }
}

Style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

build.gradle

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.1.1'
compile 'com.android.support:support-v4:22.1.1'
}

Error

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at com.example.deep.sunshine.SettingsActivity.setupActionBar(SettingsActivity.java:59)
at com.example.deep.sunshine.SettingsActivity.onCreate(SettingsActivity.java:49)
Deep
  • 673
  • 1
  • 10
  • 23
  • The following questions seem to be about the same problem: http://stackoverflow.com/q/26439139 and http://stackoverflow.com/q/27276303. The answers all seem to involve extending something else *instead of* `PreferenceActivity`. Have you seen those questions and answers? Is there something in particular you found difficult to understand about them? – Dan Getz May 23 '15 at 19:06
  • possible duplicate of [getActionBar() returns null in PreferenceActivity (AppCompat-v7 21)](http://stackoverflow.com/questions/26439139/getactionbar-returns-null-in-preferenceactivity-appcompat-v7-21) – Makoto May 23 '15 at 19:09
  • Yes - none of the answers have answered following: a. Why do we get a null reference from the getActionBar() method ? b. Why do I not get a ref to the getSupportAction bar() ? – Deep May 23 '15 at 20:34
  • Well, they **do** answer your question (b). Look, there, in your code. You're extending `PreferenceActivity`. Those answers say that to use `getSupportActionBar()`, you need to extend `ActionBarActivity`, not `PreferenceActivity`. – Dan Getz May 23 '15 at 23:29

0 Answers0