RGS
RGS

Reputation: 4253

app crashes after private NavigationView

My app crashes when I tried to add a menu there. I think the most probably thing is my private variable nn.

public class UserAreaActivity extends AppCompatActivity {

private NavigationView nn; //is it wrong?

and on onCreate

 nn = (NavigationView) findViewById(R.id.drawerLayout);
        nn.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(final MenuItem menuItem) {
                int id = menuItem.getItemId();
                switch (id) {
                    case R.id.nav_upload:
                        Intent upIntent = new Intent(UserAreaActivity.this, Upload.class);
                        UserAreaActivity.this.startActivity(upIntent);
                        return true;
                    case R.id.nav_logout:
                        SharedPreferences pref = getApplicationContext().getSharedPreferences("pref01", MODE_PRIVATE);
                        SharedPreferences.Editor editor = pref.edit();
                        editor.clear();
                        editor.apply();
                        Intent logIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
                        UserAreaActivity.this.startActivity(logIntent);
                    default:
                        return true;
                }
            }
        });

Upvotes: 0

Views: 52

Answers (1)

karique
karique

Reputation: 538

when i implement a NavigationView i didn't declare as variable in the class, just in onCreate method and then set it a listener for important things like show the menu, something like this:

NavigationView view = (NavigationView) findViewById(R.id.navigation_view);
view.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override public boolean onNavigationItemSelected(MenuItem menuItem) {
    Snackbar.make(content, menuItem.getTitle() + " pressed", Snackbar.LENGTH_LONG).show();
    menuItem.setChecked(true);
    drawerLayout.closeDrawers();
    return true;
}
});

i think you will find this link usefull: https://antonioleiva.com/navigation-view/

Upvotes: 1

Related Questions