getActionBar().setDisplayHomeAsUpEnabled(true) throws NullPointerException

android, java

Solution

You are inheriting from `ActionBarActivity`. Hence, you need to use `getSupportActionBar()`, not `getActionBar()`, to get at the `appcompat-v7`-supplied action bar backport.

Problem

This question is asked several times in stackoverflow and I have tried all of them. But unfortunately neither is working for me. I am trying to implement the navigation between two activities, as part of learning Android app development. My minium SDK and target SDK versions are 11 and 21 (Android 5), respectively. My settings in AndroidManifest.xml are shown below: ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.navigation" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="21" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".DetailActivity" > </activity> </application> </manifest> ``` I have two activities: MainActivity and DetailActivity. When I click a button in MainActivity, the app successfully opens the DetailActivity. But when I am trying to enable the back button by using the following code, it returns a NullPointerExcepion: ``` getActionBar().setDisplayHomeAsUpEnabled(true); ``` My both the classes extend ActionBarActivity. In MainActivity.java: ``` public class MainActivity extends ActionBarActivity { ... } ``` In DetailActivity.java: ``` public class DetailActivity extends ActionBarActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); getActionBar().setDisplayHomeAsUpEnabled(true); // returns null pointer } ``` I have also tried changing the themes. For example, `android:theme="@android:style/Theme.Holo.Light"`.

Original source

Related problems