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



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

主要活动

 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;
        }
    }
}

日志猫

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)

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

在这里,您告诉您的适配器它有 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。

最新更新