I am currently working on an android project and I am having a problem with contexts and AlertDialogs.
I have a class which extends a Fragment and it creates an instance of a standard Java class called Common which has the context passed to it from the Fragment. In the Common class I have some code to display an alert dialog and return a boolean based on what the user clicked.
With a standard class that extends an Activity I can create the instance of the Common class using the following:
Common common = new Common(this);
Then I can call my show alert dialog function within this class by using the following code.
common.showYesNoDialog("This is my message", false);
The code above works fine, for a standard Activity class. My problem is this.
In my Class that Extends Fragment I can’t pass this to the common class so I instead have to use the following code:
Common common = new Common(getActivity().getApplicationContext());
and I use the following code as normal:
common.showYesNoDialog("This is my message", false);
When I call the function above I get the following error:
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application.
Thanks for any help you can provide.
You should use
getActivity()instead ofgetActivity().getApplicationContext()since getActivity() returns an Activity which is a subclass of Context.