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

Posted

技术标签:

【中文标题】使用选项卡式活动和片段时应用程序崩溃【英文标题】:App crash while using tabbed activity and fragments 【发布时间】:2016-07-17 21:25:36 【问题描述】:

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

主要活动

 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)

【问题讨论】:

【参考方案1】:

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

【讨论】:

【参考方案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。

【讨论】:

以上是关于使用选项卡式活动和片段时应用程序崩溃的主要内容,如果未能解决你的问题,请参考以下文章

如何在选项卡式活动中设置片段从右到左开始

如何使用列表视图在选项卡式活动的片段中呈现 SQLite 表数据 [重复]

Android - 选项卡式片段

如何在使用片段和计时器的选项卡式活动上更新 UI

Android Studio - 选项卡式活动如何将片段重置为默认视图?

Android 选项卡式活动通过 volley 添加新片段