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

Actually Android Studio isn't showing you an "error message", it's just a warning.

Some answers propose the use of an assertion, Dalvik runtime has assertion turned off by default, so you have to actually turn it on for it to actually do something. In this case (assertion is turned off), what you're essentially doing is just tricking Android Studio to not show you the warning. Also, I prefer not to use "assert" in production code.

In my opinion, what you should do is very simple.

if(getActionBar() != null){
   getActionBar().setDisplayHomeAsUpEnabled(true);
}

Update: In case you're using the support library version of the Action Bar, you should replace getActionBar() with getSupportActionBar().

if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

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()
}