简体   繁体   中英

getSupportActionBar().setDisplayHomeAsUpEnabled(true) gives NullPOinterException

getSupportActionBar().setDisplayHomeAsUpEnabled(true) gives NullPOinterException , Ever after I tried various combinations of

  1. Activities ( AppComatActivity ),
  2. Themes( Theme.AppCompat.Light , Theme.Holo.Light ) and
  3. Up button APIs( getSupportActionBar() , getActionBar() )

I know this question had been asked many times, But believe me none of their solution worked for me.

My Motto:

I am just trying to set the Up button for my Child Activity.

Preconditions I have set:

I have set the following in Manifest file for the Child Activity

            android:parentActivityName="com.example.sony.myfirstapplication.MainActivity">

        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.sony.myfirstapplication.MainActivity"
            />

and following code in my child activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_message);

    //receive message
    Intent intent = getIntent();
    TextView txt = (TextView) findViewById(R.id.text_msg_show);
    String msg = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    txt.setText(msg);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true); //Gives NullPointerException
}

Theme in manifest file:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Style declared in Style.xml file :-

<style name="AppTheme" parent="@style/Theme.AppCompat.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

Note

I have inherited both Activities from AppCompatActivity and not ActionBarActivity

You should set your toolbar first:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSupportActionBar.setDisplayHomeAsUpEnabled(true);

Since you said it doesn't CRASH , then simply add: @SuppressWarnings("null") above that line.

Otherwise, add this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

First

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM