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?
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).
You should use the context of the Activity that it's executed from. In other words, just use YourNameOfActivity.this
as context.
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Test")
.show;
(or)
if u want (yes,no) button means use this
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.show();