My Activity is trying to create an AlertDialog which requires a Context as a parameter. This works as expected if I use:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
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 related post on the Android developer's blog:
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().
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”
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?
Jim
If you are using a fragment and using an
AlertDialog / Toast
message, usegetActivity()
in the context parameter.Worked for me.
Cheers!
In my case work:
Using
this
did not work for me, butMyActivityName.this
did. Hope this helps anyone who could not getthis
to work.In
Activity
on click of button showing a dialog boxWorked for me.
Little hack: you can prevent destroying the activity by GC (Of course, you should not do it, but it can help in some situations):
Try to use the context of an activity which will be under the dialog. But be carefull when you use "this" keyword, because it will not work everytime.
Forexample, if you have TabActivity as host with two tabs, and each tab is another activity, and if you try to create dialog from one of the tabs (activities) and if you use "this", then you will get exception, In this case dialog should be connected to host activity which host everything and visible. (you can say most visible parent Activity's context)
I did not find this info from any document but by trying. This is my solution without strong background, If anybody with better knownledge, feel free to comment.