views:

185

answers:

2

Could anyone please explain what context should i use the AlertDialog.Builder class? I am new to android app development and I frankly don't understand which context to use when?

Say, I want to create an object for AlertDialog.Builder class -

AlertDialog.Builder ab = new AlertDialog.Builder();
ab.setMessage("Test");

ab.show();

What context should I use it in? Does it differ if I use the Alert Dialog onCreate or OnClickListener or in the handler of any such event?

A: 

You should use the context of the Activity that it's executed from. In other words, just use YourNameOfActivity.this as context.

Cristian
+2  A: 

In the first version of my app I made the mistake of not using onCreateDialog and instead built and showed the dialogs myself. If you do it yourself you have to take care of things like dismissing the dialog before the activity is finish()ed otherwise a window will leak.

I would override onCreateDialog in your activity and return ab.create() (not show()). onCreateDialog will then handle showing the dialog and you'll just have to call showDialog(id).

Brandon