Question

I am trying to use ViewPager inside a Fragment and get

03-01 15:23:05.375    3937-3937/com.example.android.navigationdrawerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.example.android.navigationdrawerexample.SpaFragment.onCreateView(SpaFragment.java:50)
        at android.app.Fragment.performCreateView(Fragment.java:1695)

Code:

public class SpaFragment extends Fragment  {

    public SpaFragment(){}
    private SpaList mSpa;
    private TabHost tabs;

    private FragmentActivity mFragmentActivity;
    private View rootView;

    public void setSpa(SpaList s)
    {
        mSpa=s;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_spa, container, false);

        ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
        pager.setAdapter(new MyPagerAdapter(mFragmentActivity.getSupportFragmentManager()));

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        mFragmentActivity = (FragmentActivity) activity;
        Log.d("ACTIVITY on attach"+mFragmentActivity,"\n");
        super.onAttach(activity);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

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


        @Override
        public CharSequence getPageTitle(int position) {
            return "Title " + position;
        }

        @Override
        public android.support.v4.app.Fragment getItem(int pos) {
            switch(pos) {

                case 0: return FirstFragment.newInstance("FirstFragment, Instance 1");
                case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
                default: return FirstFragment.newInstance("ThirdFragment, Default");
            }
        }

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

No correct solution

OTHER TIPS

You are running into a NullPointerException because you are invoking a method on an object that is NULL at that time.

This could be because your

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
         // ...
    }

method is called before your

    @Override
    public void onAttach(Activity activity) { }

method, and therefore, your variable mFragmentActivity is NULL. In that case, your code

String.valueOf(mFragmentActivity);

will throw a NullPointerException.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top