So a dialog is opened every time a text is received. I want it to not open one if there is one already open. I was trying to check if one was open by using isShowing() but I keep getting the method isShowing() is undefinded for the type AlertDialog.Builder. Here is the section of bad code. Any help would be so sweet right about now.
public class PopUpReply extends Activity{
AlertDialog.Builder alertbox;
AlertDialog.Builder alert;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// prepare the alert box
alertbox.isShowing();
alertbox = new AlertDialog.Builder(this);
There is no isShowing() method on the AlertDialog.Builder class. There is one on the Dialog class though.
AlertDialog.Builder
Dialog
An AlertDialog.Builder is used to create an AlertDialog. Once you have an instance of an AlertDialog, you can determine whether or not it is still showing by then calling isShowing() on it.
Related
In my activity, I am loading some eight fragments, from the 8th fragment showing some alert dialog.After that session getting expired, so redirected them to the first fragment without user interaction.During that time alert dialog not getting closed which created from 8 fragments.
In the onPause() of your 8th Fragment you should hide the AlertDialog.
class XYZ extends Fragment{
//Keep the reference to AlertDialog as a member variable in your Fragment
AlertDialog mDialog;
//other member declarations ...
#Override
public void onPause() {
// check if dialog is not null and is already showing
if(mDialog !=null && mDialog.isHowing())
mDialog.hide();
super.onPause();
}
Note : If the viewpager removes 8th fragment from memory and some action that you perform in your dialog references your 8th fragment then it would cause null pointer exception.
If you using alert dialog like that:
AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
you need to keep the dialog instance which returns from the show method and call dismiss from that instance.
AlertDialog dialog = builder.show();
//Use this anywhere to close
dialog.dismiss();
I have a method in my class i want to test which shows an alert dialog .
When i call this method from the test class it is executed but the dialog is not shown?
The same happens when i call a method, that shows some toast or other popup dialog
my test class extends ActivityInstrumentationTestCase2.
public void showSaveName(String name){
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_menu_save)
.setTitle(R.string.savePopupLabel)
.setMessage(R.string.savePopupMessage)
.setPositiveButton(R.string.save_yes, new alter(name))
.setNegativeButton(R.string.save_no, null)
.show();
}
when i call this from my test class
getActivity().showSaveName(name);
the dialog is not shown?
Can anyone help me to figure out why it is happening ?or if i am doing something wrong?
That's normal.
Your test classes are not meant to make anything show on the device. You are supposed to programmatically make sure that the dialog appears.
In your test class, once you display the dialog, keep the instance of the Dialg box and then do
assertTrue(yourDialogInstance.isShown());
And if your dialog has not appeared, your test will fail.
That should do it.
Can you try:
public void showSaveName(String name) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(android.R.drawable.ic_menu_save)
.setTitle(R.string.savePopupLabel)
.setMessage(R.string.savePopupMessage)
.setPositiveButton(R.string.save_yes, new alter(name))
.setNegativeButton(R.string.save_no, null);
AlertDialog dialog = builder.create();
dialog.show();
}
I'd like to make a dialog fragment that asks "Are you sure?" with a "yes/no" reply.
I've looked at the documentation and it's really verbose, going all over the place, explaining how to make advanced dialog boxes, but no intact code on making a simple 'hello world' kind of dialog box. Most tutorials utilize the deprecated dialog box system. The official blog seems to be unnecessarily complicated and difficult to understand.
So, what's the simplest way to create and display a really basic Alert Dialog? Bonus points if it's using the support library.
A DialogFragment is really just a fragment that wraps a dialog. You can put any kind of dialog in there by creating and returning the dialog in the onCreateDialog() method of the DialogFragment.
Heres an example DialogFragment:
class MyDialogFragment extends DialogFragment{
Context mContext;
public MyDialogFragment() {
mContext = getActivity();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext);
alertDialogBuilder.setTitle("Really?");
alertDialogBuilder.setMessage("Are you sure?");
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", null);
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
}
To create the dialog call:
new MyDialogFragment().show(getFragmentManager(), "MyDialog");
And to dismiss the dialog from somewhere:
((MyDialogFragment)getFragmentManager().findFragmentByTag("MyDialog")).getDialog().dismiss();
All of that code will work perfectly with the support library, by just changing the imports to use the support library classes.
So, what's the simplest way to create and display a really basic Alert
Dialog? Bonus points if it's using the support library.
Simply create a DialogFragment(SDK or support library) and override its onCreateDialog method to return an AlertDialog with the desired text and buttons set on it:
public static class SimpleDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setMessage("Are you sure?")
.setPositiveButton("Ok", null)
.setNegativeButton("No way", null)
.create();
}
}
To do something when the user uses one of the buttons you'll have to provide an instance of a DialogInterface.OnClickListener instead of the null references from my code.
For those coding with Kotlin and Anko, you can now do dialogs in 4 lines of code:
alert("Order", "Do you want to order this item?") {
positiveButton("Yes") { processAnOrder() }
negativeButton("No") { }
}.show()
because of Activity / Fragment lifecycle #athor & #lugsprog approach can fail,
more elegant way is to **get activity context from method onAttach and store it as weak reference ** (&try to avoid non default constructor in DialogFragment!, to pass any argument to dialog use arguments) like this:
public class NotReadyDialogFragment extends DialogFragment {
public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_arguments";
private WeakReference<Context> _contextRef;
public NotReadyDialogFragment() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** example pulling of arguments */
Bundle bundle = getArguments();
if (bundle!=null) {
bundle.get(DIALOG_ARGUMENTS);
}
//
// Caution !!!
// check we can use contex - by call to isAttached
// or by checking stored weak reference value itself is not null
// or stored in context -> example allowCreateDialog()
// - then for example you could throw illegal state exception or return null
//
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get());
alertDialogBuilder.setMessage("...");
alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return alertDialogBuilder.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
_contextRef = new WeakReference<Context>(activity);
}
boolean allowCreateDialog() {
return _contextRef !== null
&& _contextRef.get() != null;
}
EDIT:
& if You wanna dismiss dialog then:
try to get it
check if it's exist
check if it's showing
dismiss
something like this :
NotReadyDialogFragment dialog = ((NotReadyDialogFragment) getActivity().getFragmentManager().findFragmentByTag("MyDialogTag"));
if (dialog != null) {
Dialog df = dialog.getDialog();
if (df != null && df.isShowing()) {
df.dismiss();
}
}
EDIT2: & if u wanna set dialog as non cancelable u should change onCreatweDialog return statement like this:
/** convert builder to dialog */
AlertDialog alert = alertDialogBuilder.create();
/** disable cancel outside touch */
alert.setCanceledOnTouchOutside(false);
/** disable cancel on press back button */
setCancelable(false);
return alert;
Im writing an Android application in which a user selection triggers a custom Dialog, from which a selection may trigger a second Dialog.
When showing the initial Dialog from the Activity class, I'm setting an onDismissListener on it to pull out user selections which works fine other in cases where the 2nd Dialog is not triggered. The issue that I'm having is that I can't figure out how to have the first one Dialog remain open until the 2nd one is dismissed, so that the information from both is sent back to the Activity class.
Hopefully some code will make this a little more clear:
MainActivity class where I am launching the initial CustomDialog:
customDialog = new CustomDialog(this);
customDialog.show();
customDialog.setOnDismissListener(new OnDismissListener(){
public void onDismiss(DialogInterface di){
slection = customDialog.getselection();
updateUI(); //updates a listview with the results
}
});
Within the CustumDialog class where I am launching the SecondDialog on top of it:
if(specify){
SecondDialog secondDialog = new SecondDialog(context);
secondDialog.show();
secondDialog.setOnDismissListener( new OnDissmissListener(){
public void onDismiss(DialogInterface di){
// this is where I want to call the CustomDialog's dismiss() method
// so that they both close at the same time and the data from here
// can be sent back to the MainActiivty through the CustomDialog's
// onDismissListener
}
});
}
dismiss();
So, to reiterate: I'm trying to prevent the CustomDialog's dismiss() method to be called until the SecondDialog is also dismissed. Is there a way that I can call it from the SecondDialog's OnDismissListener?
You should create customDialog as an instance level variable. You then it will be accessible with onDismiss(...) of second dialog. There you can call customDialog.dismiss();
// Instance level variable
private Dialog customDialog = null;
Instanciate your customDialog, then create second dialog from within your customDialog. Your Second dialog's code would look like this.
if(specify){
SecondDialog secondDialog = new SecondDialog(context);
secondDialog.show();
secondDialog.setOnDismissListener( new OnDissmissListener(){
public void onDismiss(DialogInterface di){
// customDialog is accessible as it is declared as instance level variable
MyClassName.this.customDialog.dismiss();
}
});
}
dismiss();
I prefer to save the data in 1st dialog before going to send one and when dismiss the 2nd dialog, open the 1st dialog again with saved data .. i used this way in my developing and its effective ..
I have a problem creating a custom dialog. But I don't find the failure. Hopefully anybody can help me ...
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_ABOUT_ID:
dialog = buildAboutDialog();
break;
default:
dialog = null;
}
return dialog;
}
...
public Dialog buildAboutDialog() {
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.about_dialog);
dialog.setTitle("About this application");
return dialog;
}
Results in the following error:
12-30 19:27:02.593: ERROR/AndroidRuntime(383): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
I checked if the returned dialog == null - but it isn't.
I also tried the second way (inflater) described at http://developer.android.com/guide/topics/ui/dialogs.html#CustomDialog
I found out, that the dialog needs to be created with
Dialog dialog = new Dialog(this);
and not
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
I don't exactly know why. Perhaps anybody can explain it to me?
Dialog dialog = new Dialog(contex);
dialog.setContentView(R.layout.help_content);
this works for me .. may be getapplicationcontext not getting context of the your main class.
As it turns out, Context of an activity is different then object returned by getApplicationContext(). This you can check by using logging, just output ActivityName.this and getApplicationContext.
The object returned by getApplicationContext is a global thing while context of an activity, well, belongs to that activity only.
Log.e(tag,""+ getApplicationContext());
Log.e(tag,""+CustomDialogActivity.this);
where CustomDialogActivity is my activity in which I want to show my dialog.
Dialogs require context of an activity and getApplicationContext() does not provide that. As written here (read comments) context of an activity is superset of getApplicationContext(). so It is a good thing to always pass context of an activity rather then the global context.
Also to answer ffleandro's comment of this page if you are inside onClick() you can use
ActivityName.this to refer to activity. Hope this helps