Android - Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference

George picture George · May 26, 2015 · Viewed 18.1k times · Source

Here is the full stack trace of the error: http://pastebin.com/5dQHkUw3

The error started to appear only after I started using fragments in the project, because I want to give JSON feeds. It was fine before when I was creating Tabs, NavigationDrawer etc.

MainActivity.java

public class MainActivity extends ActionBarActivity implements MaterialTabListener{

private Toolbar mToolbar;
private NavigationDrawerFragment mDrawerFragment;
private DrawerLayout mDrawerLayout;

private MaterialTabHost mTabHost;
private ViewPager mViewPager;

public static final int SERVICES_ALL = 1;
public static final int SERVICES_FEATURED = 2;
public static final int SERVICES_NEW = 3;

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

    mToolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    mDrawerFragment.setUp(R.id.fragment_navigation_drawer, mDrawerLayout, mToolbar);

    mTabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);
    mViewPager = (ViewPager) findViewById(R.id.viewPager);

    MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
    mViewPager.setAdapter(adapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
        @Override
        public void onPageSelected(int position) {
            mTabHost.setSelectedNavigationItem(position);
        }
    });

    for(int i=0; i<adapter.getCount(); i++ ){
        mTabHost.addTab(
                mTabHost.newTab().
                        setText(adapter.getPageTitle(i)).
                        setTabListener(this)
        );
    }
}

@Override
public void onTabSelected(MaterialTab materialTab) {
    mViewPager.setCurrentItem(materialTab.getPosition());
}

@Override
public void onTabReselected(MaterialTab materialTab) {

}

@Override
public void onTabUnselected(MaterialTab materialTab) {

}

private class MyPagerAdapter extends FragmentStatePagerAdapter{
    FragmentManager fragmentManager;

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        fragmentManager = fm;
    }

    @Override
    public Fragment getItem(int num) {
        Fragment fragment = null;
        switch (num){
            case SERVICES_ALL:
                fragment = FragmentAll.newInstance("","");
                break;
            case SERVICES_FEATURED:
                fragment = FragmentFeatured.newInstance("","");
                break;
            case SERVICES_NEW:
                fragment = FragmentNew.newInstance("","");
                break;
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return 3;
    }

    public CharSequence getPageTitle(int position){
        return getResources().getStringArray(R.array.tabs)[position];
    }
}

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

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

    if (id == R.id.action_settings) {
        Toast.makeText(this, "Hey you just hit " + item.getTitle(), Toast.LENGTH_LONG).show();
        return true;
    }

    if (id == R.id.action_next) {
        startActivity(new Intent(this, DetailActivity.class));
    }

    return super.onOptionsItemSelected(item);
}

}

FragmentAll.java (The other 2 fragments are similar to FragmentAll.)

public class FragmentAll extends Fragment {

private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

private String mParam1;
private String mParam2;

public static FragmentAll newInstance(String param1, String param2) {
    FragmentAll fragment = new FragmentAll();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

public FragmentAll() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_all, container, false);
}
}

The stacktrace:

android.support.v4.app.Fragment.setMenuVisibility(boolean)' on a null object reference
            at android.support.v4.app.FragmentStatePagerAdapter.instantiateItem(FragmentStatePagerAdapter.java:116)
            at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:836)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:986)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:918)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1440)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5463)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:430)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2560)
            at android.view.View.measure(View.java:17430)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2001)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1166)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1372)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
            at android.view.Choreographer.doCallbacks(Choreographer.java:580)
            at android.view.Choreographer.doFrame(Choreographer.java:550)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Answer

Blackbelt picture Blackbelt · May 26, 2015
public static final int SERVICES_ALL = 1;
public static final int SERVICES_FEATURED = 2;
public static final int SERVICES_NEW = 3;

should be

public static final int SERVICES_ALL = 0;
public static final int SERVICES_FEATURED = 1;
public static final int SERVICES_NEW = 2;

getItem is 0-based-index, which means that in your code, the case 0 of your Adapter never matches one, and in that case you are returning a null fragment causing the exception