使用选项卡式活动和片段时应用程序崩溃

时间:2016-07-17 21:25:36

标签: android android-fragments tabbed-view

每当我尝试滑动时,我的应用都会崩溃。以下是我的代码以及我得到的错误。

主要活动

 public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MyActivity";

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new                      SectionsPagerAdapter(    getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }
    public static class PlaceholderFragment extends Fragment {
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(    ARG_SECTION_NUMBER)));
            return rootView;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

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

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            int i=0;
            switch(position){
                case 0: return PlaceholderFragment.newInstance(position + 1);
                case 1 : return  MyFragment.newInstance();

                // default: return MyFragment.newInstance();

            }
            Log.v(TAG, "index=" + i);
            return null;
            //if you use default, you would not need to return null
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
        @Override
        public Parcelable saveState() {
            // Do Nothing
            return null;
        }

    }
}

logcat的

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.mahe.botnet3, PID: 26696
              java.lang.NullPointerException: Attempt to write to field 'android.support.v4.app.FragmentManagerImpl android.support.v4.app.Fragment.mFragmentManager' on a null object reference
                  at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:418)
                  at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:413)
                  at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:99)
                  at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:943)
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1157)
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                  at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                  at android.view.Choreographer.doFrame(Choreographer.java:549)
                  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:5343)
                  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:905)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

2 个答案:

答案 0 :(得分:3)

根据你的代码,你告诉你的适配器你有3个部分但实际上你只返回位置0和位置1的两个片段你需要在位置2返回一个片段实例

答案 1 :(得分:1)

在这里,您告诉您的适配器它有3个片段:

@Override
public int getCount() {
    // Show 3 total pages.
    return 3;
}

在你的@Override public Fragment getItem(int position)中。 你只返回2个片段。取消评论此行:

// default: return MyFragment.newInstance();

或提供另一个片段而不是MyFragment。要么使getCount返回值2。