Search code examples
androidapplicationcontextandroid-context

Passing context to a standard java class using getApplicationContext causes Force Close


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.


Solution

  • You can not use ApplicationContext in your case. Instead use just getActivity(). Activity is a Context so your Common class constructor will be satisfied.

    But your Common class should really have Common(Activity a) constructor instead.