Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context
<p>My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:</p>

<pre><code>AlertDialog.Builder builder = new AlertDialog.Builder(this);
</code></pre>

<p>However, I am leery of using "this" as a context due to the potential for memory leaks when Activity is destroyed and recreated even during something simple like a screen rotation. From a <a href="http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html" rel="nofollow">related post on the Android developer's blog</a>: </p>

<blockquote>
  <p>There are two easy ways to avoid context-related memory leaks. The most obvious one is to avoid escaping the context outside of its own scope. The example above showed the case of a static reference but inner classes and their implicit reference to the outer class can be equally dangerous. The second solution is to use the Application context. This context will live as long as your application is alive and does not depend on the activities life cycle. If you plan on keeping long-lived objects that need a context, remember the application object. You can obtain it easily by calling Context.getApplicationContext() or Activity.getApplication().</p>
</blockquote>

<p>But for the AlertDialog() neither getApplicationContext() or getApplication() is acceptable as a Context, as it throws the exception: "Unable to add window — token null is not for an application”
per references: <a href="http://stackoverflow.com/questions/1561803/android-progressdialog-show-crashes-with-getapplicationcontext">1</a>, <a href="http://stackoverflow.com/questions/2634991/android-1-6-android-view-windowmanagerbadtokenexception-unable-to-add-window">2</a>, <a href="http://groups.google.com/group/android-developers/browse_thread/thread/7a648edddccf6f7d" rel="nofollow">3</a>, etc.</p>

<p>So, should this really be considered a "bug", since we are officially advised to use Activity.getApplication() and yet it doesn't function as advertised?</p>

<p>Jim</p>
