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

前端 未结 14 2087
醉酒成梦
醉酒成梦 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:27

    Alternatively you could assert actionbar to not null.Add the assertion before calling your actionbar as follows

    assert getSupportActionBar() != null;
    

    Final snippet would therefore look as follows:

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        assert getSupportActionBar() != null;
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    
    0 讨论(0)
  • 2020-12-02 18:27
      if(getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        OR
    

    Replace the MainActivity extends AppCompatActivity to public class MainActivity extends AppCompatActivity

    0 讨论(0)
  • 2020-12-02 18:28
     if(actionBar != null) {
      actionBar.setHomeButtonEnabled(true);
      actionBar.setBackgroundDrawable(ContextCompat.getDrawable(mContext,
                                      R.drawable.action_bar_gradient));
     }
    
    0 讨论(0)
  • 2020-12-02 18:29

    add assert getSupportActionBar() != null; before getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    0 讨论(0)
  • 2020-12-02 18:32

    Try this :

    setSupportActionBar (toolbar);
    if(getSupportActionBar () != null) {
    assert getSupportActionBar () != null;
    getSupportActionBar ().setDisplayHomeUpEnabled(true);
    }
    

    Note that setSupportActionBar(toolbar) should be before getSupportActionBar().

    0 讨论(0)
  • 2020-12-02 18:36

    just check getSupportActionBar not equal to null

        setSupportActionBar(toolbar);
    
        if(getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Daily Shopping List");
        }
    
    0 讨论(0)
提交回复
热议问题