Android Box Null Pointer Exception May Occur

I keep getting this warning in my code, and I start to worry, as I am close to my deadline. I have a DrawerLayout in my main action, using the Android Studio's own box activity, but I had to make a small change to the code, because the DrawerLayout setDrawerListener is now deprecated.

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Firebase reference to main application URL and 'today's' matches Firebase mainRef = new Firebase(cons.getFirebaseUrl()); //DrawerLayout settings for the navigation drawer DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); //Retrieve the navigation drawer and set it listener for menu item presses navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); 

I get a warning on drawer.addDrawerListener(toggle) and navigationView.setNavigationItemSelectedListener(this)

Further in my code, I also get it in this method:

 @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) // This line gets the warning { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } 

Thanks in advance to everyone who may have an idea of ​​what causes him. I searched for this problem, but I could not find an example of the post postrecated method.

+5
source share
1 answer

Make sure you use ActionBarDrawerToggle in support-v7-appcompat.

Replace the code drawerLayout.setDrawerListener(actionBarDrawerToggle);

drawerLayout.addDrawerListener(actionBarDrawerToggle);

Finally, check the null box and null navigation view as follows:

  DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); assert drawer != null; drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); assert navigationView != null; navigationView.setNavigationItemSelectedListener(this); 
0
source

Source: https://habr.com/ru/post/1245873/


All Articles