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) {
}
I think you are getting null value of actionBar here:
change to
using the import:
and remember, you have to extend from
ActionBarActivity
More info: