A
A
artshelom2017-09-12 10:23:11
Android
artshelom, 2017-09-12 10:23:11

How to add NavigationView to AppCompatActivity??

I add, everything seems to be correct, but at startup it writes an error, how to fix it ??

public class UserAndTagActivity extends AppCompatActivity
        implements AppBarLayout.OnOffsetChangedListener,NavigationView.OnNavigationItemSelectedListener {


    private DrawerLayout drawer;
    public static final String TAG = "UserAndTagFragment";

    private static final int PERCENTAGE_TO_ANIMATE_AVATAR = 20;
    private boolean mIsAvatarShown = true;
    private Toolbar toolbar;

    private int mMaxScrollSize;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.collapsing_toolbar_layout);

        this.url = getIntent().getStringExtra("url");

        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.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        


        TabLayout tabLayout = (TabLayout) findViewById(R.id.materialup_tabs);
        ViewPager viewPager  = (ViewPager) findViewById(R.id.materialup_viewpager);
        AppBarLayout appbarLayout = (AppBarLayout) findViewById(R.id.materialup_appbar);

        toolbar = (Toolbar) findViewById(R.id.materialup_toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                onBackPressed();
            }
        });

        setSupportActionBar(toolbar);

        appbarLayout.addOnOffsetChangedListener(this);
        mMaxScrollSize = appbarLayout.getTotalScrollRange();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager.setAdapter(new TabsAdapter(getSupportFragmentManager()));
        tabLayout.setupWithViewPager(viewPager);
    }

Mistake:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference

The same code in the main activity works fine

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexeyVD, 2017-09-12
@artshelom

findViewById(R.id.drawer_layout) returned NULL to you. Check if there is a drawer_layout element in your collapsing_toolbar_layout. And I advise you to use butterknife to catch such errors at the compilation stage.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question