Note that there are some explanatory texts on larger screens.

plurals
  1. PODialog throwing "Unable to add window — token null is not for an application” with getApplication() as context
    text
    copied!<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="noreferrer">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 <code>AlertDialog()</code> neither <code>getApplicationContext()</code> or <code>getApplication()</code> is acceptable as a Context, as it throws the exception: </p> <blockquote> <p>"Unable to add window — token null is not for an application”</p> </blockquote> <p>per references: <a href="https://stackoverflow.com/questions/1561803/android-progressdialog-show-crashes-with-getapplicationcontext">1</a>, <a href="https://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="noreferrer">3</a>, etc.</p> <p>So, should this really be considered a "bug", since we are officially advised to use <code>Activity.getApplication()</code> and yet it doesn't function as advertised?</p> <p>Jim</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload