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
Activity activity;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity=activity;
}
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;
}
replace getActivity() to A.this
AlertDialog.Builder alert = new AlertDialog.Builder(A.this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With