Android - App crashes, using Swipe Tab Views

678 views Asked by At

I have looked at every tutorial on the Internet about swipeable tab views with Android. Every time I use a different code, it crashes! The logcat gives this error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual      
     method 'void android.app.ActionBar.setNavigationMode(int)' on a null 
     object reference

I have no idea why this does not work. Here is my MainActivity code:

public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

private ViewPager viewPager;
private ActionBar actionBar;
private TabsPagerAdapter tabPagerAdapter;
private String[] tabs = {"Missed Calls", "Dialled", "Received"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewPager = (ViewPager) findViewById(R.id.pager);
    tabPagerAdapter = new TabsPagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(tabPagerAdapter);

    actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        /**
         * on swipe select the respective tab
         * */
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
1

There are 1 answers

0
Jorgesys On BEST ANSWER

I think you are getting null value of actionBar here:

actionBar = getActionBar(); 
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

change to

actionBar = getSupportActionBar(); 

using the import:

import android.support.v7.app.ActionBarActivity;

and remember, you have to extend from ActionBarActivity

public class MainActivity extends ActionBarActivity {

More info:

If you are using the support library

import android.support.v7.app.ActionBarActivity;

public class MainActivity extends ActionBarActivity {

use getSupportActionBar() instead of getActionBar()