-1

When trying to run the app and swipe between views the app crashes with a null object reference error. I have double checked my getItem method to make sure it would handle this but the app still crashes. The application runs the first view fine but crashes when trying to swipe to the second and third.

Will appreciate if anyone can clarify what the error is.

I have also included the error log below the code.

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

This is the error Log;

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)

Mostafa Arian Nejad
  • 1,278
  • 1
  • 19
  • 32
coding95
  • 27
  • 1
  • 8

1 Answers1

1

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.

Ben P.
  • 52,661
  • 6
  • 95
  • 123