Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what context should i use AlertDialog.Builder in?

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?

like image 420
pavanred Avatar asked Jul 24 '10 18:07

pavanred


People also ask

What is the context for AlertDialog builder?

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

How do I use AlertDialog builder?

Alert Dialog code has three methods:setTitle() method for displaying the Alert Dialog box Title. setMessage() method for displaying the message. setIcon() method is used to set the icon on the Alert dialog box.

What is the use of AlertDialog?

AlertDialog. A dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. DatePickerDialog or TimePickerDialog. A dialog with a pre-defined UI that allows the user to select a date or time.

What is the difference between dialog and AlertDialog?

AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .


3 Answers

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

like image 105
Cristian Avatar answered Nov 15 '22 18:11

Cristian


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).

like image 37
Brandon O'Rourke Avatar answered Nov 15 '22 18:11

Brandon O'Rourke


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();
like image 22
K.Muthu Avatar answered Nov 15 '22 19:11

K.Muthu