-1

I'm getting (AS) warnings and a null pointer when trying to enable the "UP Navigation" on an activity.

: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference

I've tried two different methods (Display Back Arrow on Toolbar Android) but without success.

What am I doing wrong?

public class ViewMyHistory extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_requests);

        Toolbar appToolbar = (Toolbar) findViewById(R.id.mainToolbar);
        setSupportActionBar(appToolbar);

        //This gives errors
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

        //and so does this
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}
Maxcot
  • 1,513
  • 3
  • 23
  • 51

2 Answers2

1

Your code is okay. The only possible problem is that you may not have a Toolbar with id R.id.mainToolbar inside your layout file R.layout.my_requests.

If you don't want to use a Toolbar, use an appcompat theme with an action bar as the parent theme of your AppTheme(or whatever your activity is using) in styles.xml such as Theme.AppCompat.Light.DarkActionBar

Nabin Bhandari
  • 15,949
  • 6
  • 45
  • 59
0

You can use either one of this :

 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// OR 
 getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
Kumar Raj
  • 124
  • 1
  • 10