Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Arpit Jhunthra
PLUS
Arpit Jhunthra
Courses Plus Student 736 Points

IllegalStateException about themes when trying to include the action bar in an activity with fragments

I have an activity with 3 fragments which extends AppCompatActivity and implements ActionBar.TabListener, and I wanted to make the action bar visible for each of the fragments as I'm also using a SearchView in the fragments:

SearchView sv = new SearchView((getActivity()).getActionBar().getThemedContext());

So I added android:theme="@android:style/Theme.Holo.Light.DarkActionBar" to this activity's tag in the Android Manifest (a quick fix that I picked up on the Ribbit app forum).

However, now when I run the app, I get an error "java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity". I understand this is probably due to my quick fix for the action bar, but I'm not aware of any other method for including the action bar as well as having fragments in the activity. Here's my code for the activity:

import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;

public class SearchAndAdd extends AppCompatActivity implements ActionBar.TabListener { //add new people to follow

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SearchAndAddAdapter mSearchAndAddAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSearchAndAddAdapter = new SearchAndAddAdapter(this, getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSearchAndAddAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSearchAndAddAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSearchAndAddAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }


    @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_search_and_add, 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);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

}

Here's my code for the adapter used in the above activity:

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.Locale;

public class SearchAndAddAdapter extends FragmentPagerAdapter {

    protected Context mContext;

    public SearchAndAddAdapter(android.content.Context context, FragmentManager fm) {
        super(fm);
        mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0: return new ManualSearchFragment(); //manual search
            case 1: return new LoginFragment();
            case 2: return new SignUpFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return mContext.getString(R.string.title_manual_search).toUpperCase(l);
            case 1:
                return mContext.getString(R.string.title_login).toUpperCase(l);
            case 2:
                return mContext.getString(R.string.title_signup).toUpperCase(l);

        }
        return null;
    }
}

Any help will be greatly appreciated! Ben Jakuben, I had the same problem in the Ribbit App.

1 Answer

Ben Deitch
STAFF
Ben Deitch
Treehouse Teacher

Have you tried using a Theme.AppCompat theme? So instead of Theme.Holo.Light.DarkActionBar, try Theme.AppCompat.Light.DarkActionBar.

Arpit Jhunthra
Arpit Jhunthra
Courses Plus Student 736 Points

Thanks for your reply! I changed the theme in the manifest, and thankfully, this time the activity did open. But I got a new error :/

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.app.ActionBar.getThemedContext()' on a null object reference

This happens on this line in one of the fragments:

SearchView sv = new SearchView((getActivity()).getActionBar().getThemedContext());