Search code examples
androidandroid-fragmentsandroid-actionbarandroid-appcompatandroid-actionbar-compat

android getSupportActionBar() returns null in fragment


UPDATE

I had not mentioned anything about using ToolBar with ActionBarActivity. And that is the reason I always get null pointer exception. For those who face same problem please refere this answer


I have this fragment code to change appearance of support action bar when fragment is changed.

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        mActionBar = ((ActionBarActivity)getActivity()).getSupportActionBar();
        SpannableString s = new SpannableString("Dashboard");
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.app_blue_text)), 0, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        s.setSpan(new TypefaceSpan(getActivity(), "Optima-Regular.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        if( null!= mActionBar){
            mActionBar.setElevation(0);
            mActionBar.setTitle(s);
        }
    }

I've referred previous/similar questions regarding how to solve this error. Those solutions suggest to change actionbar appearance in onActivityCreated() method. I tried onAttach() also. None seems to work. I have used support actionbar to maintain backward compatibility. Activity is also casted accordingly to ActionBarActivity.

Complete code is pretty much lengthy so I have skipped posting it. If needed I can post complete code and update question with more details as well.

Error log

Caused by: java.lang.NullPointerException
            at com.example.testapp.fragments.NavigationDrawerFragment.onActivityCreated(NavigationDrawerFragment.java:215) 

Line 215 is : mActionBar.setElevation(0);


Solution

  • I missed mentioning little more info in this question. That's the reason other nice SO users could not answer it correctly. So here I answer it my own.

    I've used ToolBar in place of regular ActionBar. When you use ToolBar you have to set it as ActionBar. So by doing -

    toolbar = (Toolbar) getActivity().findViewById(toolbarId);
    ((ActionBarActivity)getActivity()).setSupportActionBar(toolbar);
    

    And after that I can change title and appearance easily by -

    ((ActionBarActivity)getActivity()).getSupportActionBar().setTitle(s);
    

    Just remember to set toolbar as actionbar before actually using actionbar in fragment.