首页 > 解决方案 > Swipeable Views Null 异常错误 - Android Studio

问题描述

当尝试运行应用程序并在视图之间滑动时,应用程序崩溃并出现空对象引用错误。我已经仔细检查了我的 getItem 方法以确保它可以处理这个问题,但应用程序仍然崩溃。该应用程序可以正常运行第一个视图,但在尝试滑动到第二个和第三个视图时崩溃。

如果有人能澄清错误是什么,将不胜感激。

我还在代码下方包含了错误日志。

public class MainActivity extends AppCompatActivity {

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

}


@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) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    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) {
        //returning the current tabs
        switch (position){
            case 0:
                Tab1 tab1 = new Tab1();
                return tab1;
            case 1:
                Tab2 tab2 = new Tab2();
                return tab2;
            case 3:
                Tab3 tab3 = new Tab3();
                return tab3;
            default:
                return null;
        }
    }

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

这是错误日志;

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:394) at android.support.v4.app.BackStackRecord.add(BackStackRecord.java:389) at android.support.v4.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:104) at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:1002) at android.support.v4.view.ViewPager.populate(ViewPager.java:1216) at android.support.v4.view.ViewPager.populate(ViewPager.java:1084) at android.support.v4.view.ViewPager$3.run(ViewPager.java:267) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:911) at android.view.Choreographer.doCallbacks(Choreographer.java:723) at android.view.Choreographer.doFrame(Choreographer.java:655) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:897) at android.os.Handler.handleCallback(Handler.java:790) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

标签: javaandroidandroid-studioviewandroid-tablayout

解决方案


The problem is in this code:

@Override
public Fragment getItem(int position) {
    //returning the current tabs
    switch (position){
        case 0:
            Tab1 tab1 = new Tab1();
            return tab1;
        case 1:
            Tab2 tab2 = new Tab2();
            return tab2;
        case 3:
            Tab3 tab3 = new Tab3();
            return tab3;
        default:
            return null;
    }
}

Specifically, this line:

case 3:

This should be case 2 instead. As it is now, you'll return null from the default case for your third page.


Incidentally, I recommend changing how you handle situations like this going forward. Instead of returning null from the default case, I think you should do this:

case default:
    throw new IllegalArgumentException("unexpected position: " + position);

If you'd had this in place instead of return null, your error would have been much more obvious. You'd have seen

IllegalArgumentException: unexpected position: 2

Which would have helped you realize the typo in case 3.

In general, you should always throw an exception instead of returning some default value when your program is in a place it shouldn't be.


推荐阅读