Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method invocation 'setDisplayHomeAsUpEnabled' may produce 'java.lang.NullPointerException

Tags:

android

Why this line produce NullPointerException?

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

I have imported android.support.v7.app.AppCompatActivity in build.grade I am using com.android.support.design:25.0.1

public class PhotosActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos_activity);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            // finish the activity
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Errors: http://pastebin.com/aCQ4Hvpi

like image 545
Defus Avatar asked Oct 17 '25 19:10

Defus


1 Answers

This conditional will fix that warning:

if (getSupportActionBar() != null) {

This is how I have my SupportActionBar set up, maybe this will help!

Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_top);
    setSupportActionBar(myToolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
    }
like image 101
Nick Friskel Avatar answered Oct 19 '25 09:10

Nick Friskel