I am working on an android app and am currently having a problem with passing contexts to a standard Java class from a ListFragment.
I have a class called Common and in the constructor I pass the context so I can do various common tasks, such as displaying an alert dialogue, so that I can keep reusing the code instead of having to write the code out each time for every alert dialog box I need. To initialise the class in a standard activity I am using.
Common common = new Common(this);
The code above works fine if this is done in a class that extends an Activity. However, if I want to do the same sort of thing but in a class that extends a ListFragment, this doesn’t work, so I use the following code in order initialise the class
Common common = new Common(getActivity().getApplicationContext());
When the above code is executed in the ListFragment, when a function is used to display a Yes/No alert dialogue I get a force close with the exception
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window
--token null is not for an application
Below is the code for the constructor for the class
public Common(Context context)
{
this.context = context;
}
Just to reiterate, all of the functions within the Common class, including the Yes/No dialogue work fine without problems if the Common class is initialised from a class that extends Activity using the this argument passed to the constructor. Its only if I getActivity().getApplicationContext() as an argument passed to the constructor that I get this error.
As a test I have also changed one my classes that extends an activity and used the getApplicationContext instead of using this, and I get the same error, so its not necessarily specific to me using a ListFragment.
Thanks for any help you can provide.
You can not use
ApplicationContextin your case. Instead use justgetActivity(). Activity is aContextso yourCommonclass constructor will be satisfied.But your
Commonclass should really haveCommon(Activity a)constructor instead.