Search code examples
javaandroidandroid-fragmentstabsswipe

I am trying to make the swipeable tab layout in android but getting null value in action bar


I am trying to make the two tab layout for {profile} and {Child} which should be swipeable too. I have created the layout and fragment for both of them and on Main Activity layout, I have put

<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">

And in my Main Activity.java class my code is

import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;

// Tab titles
private String[] tabs = {"Profile", "Child"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit);

    // Initialization
    viewPager = (ViewPager) findViewById(R.id.pager);

    actionBar = (ActionBar) getSupportActionBar();

    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

But here in actionBar, I am getting null value, so program execute with null pointer at that point. Due to what reason, null might be coming in getActionBar.


Solution

  • Change your activity theme to @style/Theme.AppCompat or define toolbar in your layout:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:minHeight="?attr/actionBarSize"
            android:background="?attr/colorPrimary" />
    
        <android.support.v4.view.ViewPager
             android:id="@+id/pager"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    
    </RelativeLayout>
    

    And set custom action bar:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);
    
        Toolbar toolbar = (Toolbar) findViewById(toolbar);
        setSupportActionBar(toolbar);
    
        actionBar = (ActionBar) getSupportActionBar();
    }
    

    ActionBar tabs is deprecated and not working since API 21. You should use PagerSlidingTabStrip library.