I want to implement the Android ActionBar back button in my StreamActivity but I'm getting this error :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.schoolteacher/com.example.schoolteacher.StreamActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
I don't know why this is not working, despite I followed all instructions from the documentation! plus, I did exactly this in other projects and it works.
Here is my code :
StreamActvivty.java
public class StreamActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
styles.xml
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
manifest
<activity android:name=".StreamActivity"
android:label="@string/stream"
android:parentActivityName=".ClassActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ClassActivity" />
</activity>
Try this
Add this in onCreate
ActionBar actionBar = this.getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
Add this outside of the onCreate, this is used to navigate back to the parent activity
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
And also set Parent activity
<activity
android:name=".activity.CreateAccountActivity"
android:parentActivityName=".activity.LoginActivity" />