getActivity().getActionBar() is giving null on fragment Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of getActivity().getActionBar() is giving null on fragment without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a fragment , where I need to change the title of ActionBar dynamically. But when I am using the following code, it is giving me NullPointerException. Here getActionBar() is returning null,my question is how can I get the reference of ActionBar in Fragment class. Appreciate your help in advance.

Fragment Class code:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      ActionBar mActionBar = getActivity().getActionBar();
      mActionBar.setTitle("Your new score is :"+ i);
      return rootView;
}

Answer

I think the best solution is make a call back from your fragment like below:

Create a call back

public interface OnActionBarListener {
        void onChangeActionBarTitle(int score);
    }

and implement it in your activity

public class YourActivity extends AppCompatActivity
        implements OnActionBarListener {
    @Override
    public void onChangeActionBarTitle(int score) {
       mActionBar.setTitle("Your new score is :"+ score);
    }
}

and in your fragment

public class YourFragment extends Fragment {
    OnActionBarListener mListener;

 @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof YourActivity) {
            mListener = (OnActionBarListener) context;
        }

    }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       if (mListener != null) mListener.onChangeActionBarTitle(i);
       return rootView;
}

}

Hope this helps !

UPDATE 1: base on your request, if you want your activity listen every button click on your fragment, try below code in your fragment

Button mButton1;
Button mButton2;

mButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeTitle(your_score);
            }
        });
mButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeTitle(your_score);
            }
        });

void changeTitle(int score) {
        if (mListener != null) mListener.onChangeActionBarTitle(i);
    }
We are here to answer your question about getActivity().getActionBar() is giving null on fragment - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji