How to fix getActionBar method may produce java.lang.NullPointerException

前端 未结 14 2272
醉酒成梦
醉酒成梦 2020-12-02 18:06

I am using a toolbar as my actionbar in an activity. I am trying to add the method getActionBar().setDisplayHomeAsUpEnabled(true); to the Activity.java file fo

14条回答
  •  情书的邮戳
    2020-12-02 18:51

    First off, you need to set the toolbar as the support ActionBar. Then if you're certain it's going to be there all the time, just assert it as != null. This will tell the compiler it won't be null, so the null check passes.

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.cardviewinput);
    
       Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
       setSupportActionBar(toolbar);
    
       assert getSupportActionBar() != null;
       getSupportActionBar().setDisplayHomeAsUpEnabled(true); // it's getSupportActionBar() if you're using AppCompatActivity, not getActionBar()
    }
    

提交回复
热议问题