I am looking to build the swipe view with tabs function in my application by following a tutorial that I found on one of the answers in the forum
[http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/]
But I keep getting a null pointer error which I cant seem to find out why? I have strictly followed the tutorial and also read other similar questions about swipe views on forum. The coding are practically identical to what I have at the moment. But every time I run the emulator I get this error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.swipe/com.example.tim.swipe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActionBar$Tab android.app.ActionBar.newTab()' on a null object reference
I assume its something to do with the ActionBar but the codes from the tutorial and other sources are practically the same.
MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
ViewPager viewPager;
TabsPagerAdapter adapter;
ActionBar actionBar;
String[] tabs = { "FragmentA", "FragmentB", "FragmentC" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
adapter = new TabsPagerAdapter(getSupportFragmentManager());
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
TabsPageAdapter.java
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// Top Rated fragment activity
return new FragmentA();
case 1:
// Games fragment activity
return new FragmentB();
case 2:
// Movies fragment activity
return new FragmentC();
}
return null;
}
@Override
public int getCount() {
return 3;
}
FragmentA
public class FragmentA extends Fragment {
public FragmentA() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
return rootView;
}
FragmentB and FragmentC has the same code except for their layouts.