Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getActivity() is null inside AlertDialog of a fragment

Why the getActivity() is returning null inside AlertDialog ?

This is the class -

Class A extends Common{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        Button save = (Button) view.findViewById(R.id.save);
        save.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        System.out.println("the activity outside dialog.."+getActivity());

        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setPositiveButton("Check acitivity", 
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, 
            int whichButton) {
            dialog.cancel();
            System.out.println("the activity inside dialog.."+getActivity());
            }
         });
      }
}

The Common class is extending fragment as -

import android.support.v4.app.Fragment;
Class Common extends Fragment
{
  //Some code
}

And the output is -

the activity outside dialog..com.testapp.main.MainActivity@42131080
the activity inside dialog..null
like image 463
My God Avatar asked Jul 22 '14 07:07

My God


3 Answers

 Activity activity;
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.activity=activity;
}
like image 110
Sudhi S Avatar answered Oct 19 '22 15:10

Sudhi S


i think getActivity() inside DialogInterface is pointing to the context of dialog

dialog.getActivity()

inside your DialogInterface try changing it to :

A.this.getActivity();

Edit : i've checked the getActivity() inside DialogInterface and it should work just fine.

another solution might be using onAttach Callback function and get your activity Context there to be sure that your Fragment attached to the parent activity before using it in dialog. then use it instead of getActivity().

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    yourActivity = activity;
}
like image 4
Arash GM Avatar answered Oct 19 '22 16:10

Arash GM


replace getActivity() to A.this

AlertDialog.Builder alert = new AlertDialog.Builder(A.this);
like image 1
Minp Avatar answered Oct 19 '22 15:10

Minp