-2

i am creating an android app that uses a Navigation Drawer. Since i will have more than one Option in the drawer, i had to create a method passing the activity that i want to implement the navigation and the Activity Toolbar.

The problem is, i am receiving a Null Pointer when i declare the NavigatioDrawer method in the activities. let me show you:

HERE IS MY NAVIGATION DRAWER METHOD(WHICH I WILL INSTANTIATE IN THE ACTIVITY):

        package studio.brunocasamassa.ajudaaqui.helper;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;

import studio.brunocasamassa.ajudaaqui.MainActivity;
import studio.brunocasamassa.ajudaaqui.PerfilActivity;
import studio.brunocasamassa.ajudaaqui.R;
import studio.brunocasamassa.ajudaaqui.ConfiguracoesActivity;
import studio.brunocasamassa.ajudaaqui.ChatActivity;
import studio.brunocasamassa.ajudaaqui.GruposActivity;
import studio.brunocasamassa.ajudaaqui.PedidosActivity;
import studio.brunocasamassa.ajudaaqui.SobreActivity;

/**
 * Created by bruno on 24/04/2017.
 */

public class NavigationDrawer {


    //NAVIGATION DRAWER
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    //private static Activity setClasse = new Activity();
    private static MainActivity main;
    private static User usuario = main.user;

    public void createDrawer(final Activity classe, Toolbar toolbar) {
        //setClasse = classe;
        //Itens do Drawer
        PrimaryDrawerItem item1 = new PrimaryDrawerItem().withIdentifier(1).withName(R.string.menu_pedidos);
        PrimaryDrawerItem item2 = new PrimaryDrawerItem().withIdentifier(2).withName(R.string.menu_chats);
        PrimaryDrawerItem item3 = new PrimaryDrawerItem().withIdentifier(3).withName(R.string.menu_grupos);
        PrimaryDrawerItem item4 = new PrimaryDrawerItem().withIdentifier(4).withName(R.string.menu_perfil);
        PrimaryDrawerItem item5 = new PrimaryDrawerItem().withIdentifier(5).withName(R.string.menu_configuracoes);
        PrimaryDrawerItem item6 = new PrimaryDrawerItem().withIdentifier(6).withName(R.string.menu_sobre);

        // Create the Navigation Drawer AccountHeader
        AccountHeader headerResult = new AccountHeaderBuilder()
                .withActivity(classe)
                .withHeaderBackground(R.color.colorPrimary)
                .addProfiles(
                        new ProfileDrawerItem().withName("User").withEmail("user@example.com").withIcon(usuario.getProfileImageURL())
                )
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
                        return false;
                    }
                })
                .build();

        //Definition Drawer
        Drawer drawer = new DrawerBuilder()
                .withActivity(classe)
                .withToolbar(toolbar)
                .withAccountHeader(headerResult)
                .addDrawerItems(
                        item1,
                        new DividerDrawerItem(),//Divisor
                        item2,
                        new DividerDrawerItem(),//Divisor
                        /*DIVISAO COM MENSAGEM new SectionDrawerItem().withName(R.string.section),//Seção*/
                        item3,
                        new DividerDrawerItem(),//Divisor
                        item4,
                        new DividerDrawerItem(),//Divisor
                        item5,
                        new DividerDrawerItem(),//Divisor
                        item6
                        //Divisor
                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                        StartActivity a = new StartActivity()   ;
                        a.verifyActivity(classe, position);
                        return false;
                    }
                })
                .withSelectedItemByPosition(0)
                .build();
    }


}


class StartActivity extends AppCompatActivity {


    public void verifyActivity(Activity classe, int position) {
        if (position == 1) {
            // HERE I AM TRYING USING DIFFERENT FORMS TO START THE ACTITIVIES
            startActivity(new Intent(classe, PedidosActivity.class));
        }
        if (position == 3) {
            startActivity(new Intent(classe, ChatActivity.class));
        }
        if (position == 5) {
            startActivity(new Intent(classe, GruposActivity.class));
        }
        if (position == 7) {
            startActivity(new Intent(classe, PerfilActivity.class));
        }
        if (position == 9) {
            startActivity(new Intent(classe, SobreActivity.class));
        }
    }

}

HERE IS MY PedidosActivity(i call the navigator here):

    package studio.brunocasamassa.ajudaaqui;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;

import com.facebook.login.LoginResult;

import studio.brunocasamassa.ajudaaqui.helper.NavigationDrawer;
import studio.brunocasamassa.ajudaaqui.helper.PedidosTabAdapter;
import studio.brunocasamassa.ajudaaqui.helper.SlidingTabLayout;
import studio.brunocasamassa.ajudaaqui.helper.User;

/**
 * Created by bruno on 24/04/2017.
 */

public class PedidosActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private ListView listview_nomes;
    private ViewPager viewPager;
    private SlidingTabLayout slidingTabLayout;
    public int posicao;
    private LoginResult loginResult;
    private MainActivity main;
    private User usuario;
    private static NavigationDrawer navigator = new NavigationDrawer();


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello);

        toolbar = (Toolbar) findViewById(R.id.toolbar_principal);
        toolbar.setTitle(getResources().getString(R.string.menu_pedidos));
        //toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimaryDark));
        setSupportActionBar(toolbar);

        /*
        loginResult = MainActivity.lr;
        Profile profile = Profile.getCurrentProfile();
        System.out.println("PROFILE: "+ profile);

        String userid = loginResult.getAccessToken().getUserId();
        String name = message(profile);
        user.setName(name);*/

        usuario = main.user;
        System.out.println("USER: " + usuario.getName());
        String username = usuario.getName();
        loginResult=main.lr;
        String userImg = usuario.getProfileImg();

        listview_nomes = (ListView) findViewById(R.id.ListContatos);
        viewPager = (ViewPager) findViewById(R.id.vp_pagina);
        slidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
        slidingTabLayout.setDistributeEvenly(true);
        slidingTabLayout.setSelectedIndicatorColors(ContextCompat.getColor(this, R.color.colorAccent));

        PedidosTabAdapter pedidosTabAdapter = new PedidosTabAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pedidosTabAdapter);

        slidingTabLayout.setViewPager(viewPager);


        navigator.createDrawer(PedidosActivity.this, toolbar);


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.action_exit:
                //logoutUser();
                return true;
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }


}

If someone could help, it will be very grateful

Aury0n
  • 217
  • 3
  • 14
  • In which line you got NPE? Write it in answer please. – Aleksandr Podkutin Apr 26 '17 at 14:07
  • Can you paste the exception message please. – Crash Apr 26 '17 at 14:09
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Gary99 Apr 26 '17 at 15:47
  • If `NavigationDrawer` is not being used as an `Activity`, it should not extend `AppCompatActivity`. – Mike M. Apr 26 '17 at 22:29
  • @AlexanderPodkutin i got NPE in the " navigator.createDrawer(PedidosActivity.this, toolbar); " line – Aury0n Apr 27 '17 at 18:00
  • Remove `extends AppCompatActivity` from `NavigationDrawer`, and note the errors that will then show in the class. If you read further on in that stack trace, you should see that the line that's actually throwing the Exception is one of those with an error now. – Mike M. Apr 28 '17 at 01:18
  • @MikeM. i just do that, the problem is in the onItenClickListenter startActivity . it says **java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference** – Aury0n Apr 28 '17 at 17:31
  • You can't instantiate an `Activity` with `new` and have it work correctly. That's why you're having these issues. Your `NavigationDrawer` now extends `MainActivity` - used to be `AppCompatActivity` - and you're creating an instance of that with `new` in `PedidosActivity`. Everywhere you need an `Activity`/`Context` in `NavigationDrawer`, use the `Activity` you pass it - `Activity classe` in the `createDrawer()` method. If you remove `extends MainActivity`, you should see some places where you need to change that. Also, remove the `new Activity()` initialization from `Activity setClasse`. – Mike M. Apr 28 '17 at 20:55
  • Hi @MikeM., by doing that, i have issues in the startActivity method because it has not yet imported (that is why i couldn't exclude the 'extends Main Activity or AppCompatActivity') i tried to created another class inside my NavigationDrawer class just to make the Activities transition for me, but the problem still appears... i will post the update now – Aury0n Apr 29 '17 at 19:02
  • Yes, that's the exact same issue. You're extending `Activity` in a class that's not being used as an `Activity`. Only the system can properly instantiate and initialize an `Activity`, which is why you get those Exceptions. You keep extending an `Activity` so you can use `startActivity()`. Don't do that. Call `startActivity()` on the `Activity` you're passing in. – Mike M. Apr 30 '17 at 03:10

1 Answers1

0

ITS WORKED, tks @MikeM, it was that what you said. Here is the answer

this method i call inside the Drawer onClickListener;

   private void verifyActivity(Activity classe, int position) {
            if (position == 1) {
                // HERE I AM TRYING USING DIFFERENT FORMS TO START THE ACTITIVIES
                classe.startActivity(new Intent(classe, PedidosActivity.class));
            }
            if (position == 3) {
                classe.startActivity(new Intent(classe, ChatActivity.class));
            }
            if (position == 5) {
                classe.startActivity(new Intent(classe, GruposActivity.class));
            }
            if (position == 7) {
                classe.startActivity(new Intent(classe, PerfilActivity.class));
            }
            if (position == 9) {
                classe.startActivity(new Intent(classe, SobreActivity.class));
            }

here i call that, for each activity:

  NavigationDrawer navigator = new NavigationDrawer();

        navigator.createDrawer(PerfilActivity.this, toolbar);
Aury0n
  • 217
  • 3
  • 14