How to close a Dialog in Android programmatically? - java

How do I close a Dialog in android programmatically for example by a button?
Imagine I have a Dialog with a OK button on it, and want to close it by OK button, but I cant do that!
I googled and found nothing useful, and almost all of them for closing AlertDialog not a Dialog.

You can call dismiss on the dialog.

This is an example of how to create a AlertDialog with 2 Buttons (OK and cancel).
When clicking the cancel button,
dialog.dismiss()
is called to close the dialog.
From anywhere outside, you could call
builder.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Some message.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do something
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
builder.show();

dialog.dismiss();
Only this line will close it. :-)
Implement it in the onClickListener.

You can use the methods cancel() or dismiss(). The method cancel() essentially the same as calling dismiss(), but it will also call your DialogInterface.OnCancelListener (if registered).

Alternative to the dismiss(); option, if you have your dialog as a separate Activity (s.a. DialogActivity), another way to close it is to call:
finish();
Call this method inside the OnClickListener class' onClick() method.
This will call the onPause(), onStop() and onDestroy() methods consequently and kill the current activity - same as Back button.

Related

android studio exit confirmation dialogue not working

public void exit(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher_round);
builder.setTitle("Likee Likes");
builder.setMessage("Do you really wanna Exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.create();
builder.show();
}
**I am using this code to confirm my user either exit or not. when my user click the "yes" button the app doesn't close and get back to the previous activity. Is there any mistake with this code? **
i am trying to close my app by user confirmation.
I assumes you use AlertDialog in the another activity rather than your first activity, so when you use finish, you are close the activity that isn't the first activity.
If you you want to close you app, you can try use startActivityForResult to process some job accordingto the requestCode.
But now startActivityForResult is deprected, you can try to use new way to do this: OnActivityResult method is deprecated, what is the alternative?.
You can reference to this too How to quit android application programmatically

Android AlertDialog doesn't get displayed while calling from one method but it gets displayed from another method in the same activity. Why?

I am in an activity and I am trying to display an alert dialog. The code is this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("xx");
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
built.dismiss();
}
});
builder.setNegativeButton(R.string.giveup, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
built.dismiss();
}
});
builder.setCancelable(true);
built = builder.create();
built.show();
The thing is, the same code is called in two different places in the activity and one works while the other doesn't! I don't understand because they are literally the same...
There are questions like this in this site and I tried most of them. I changed the this in the parameter to the activity name, I set a position, I put show() method, etc... I do not know how to proceed
And I put breakpoints in both of the places. The working one goes smoothly. But when it does not get displayed, the breakpoint crashes at 'builder.create()'. It doesn't go further than this (it doesnt see the next breakpoint which is built.show). It says "frames are not available"
I found it. Just putting it here in case someone needs it. I found it from here: Listener method (interface in Service) in my Activity doesn't want to display a simple message
The problem was that, I was calling the "not-working" one from an emitter.listener, thus it was not working on the correct thread. We need this to work on UI thread. When I added this:
runOnUiThread(new Runnable(){
public void run(){
showAlertDialog();
}
});
It worked!

java Android - two dialogs, prevent first dialog from closing after second one exits

Initially in my app I am creating an AlertDialog which has three buttons, in which the middle button opens up another AlertDialog. The problem is that when the second AlertDialog closes after a button is pressed, the first one closes with it. I think both AlertDialogs get closed after I press a button on the second AlertDialog.
What I want is for the first AlertDialog to open another AlertDialog that has its own buttons, and when second AlertDialog presses a button, it only closes itself and goes back to the first one. Is there any way to achieve this?
Here is the code for the button used to open the AlertDialog:
final ImageButton fabgroup = (ImageButton) findViewById(R.id.groupButton);
Here's the code for a button that opens an AlertDialog that contains another button that opens another AlertDialog using the middle button (create button) on itself, but closes them both when a button on the second one is pressed (either the yes or no button, which is not what I want as I only want the second one to close itself and go back to the first AlertDialog, and yea this sounds pretty confusing in theory so I can try to clarify if needed):
fabgroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(CreateNote.this);
helpBuilder.setTitle("Select a group");
helpBuilder.setMessage("Add to group?");
final TextView input = new TextView(mainactiv.this);
input.setSingleLine();
input.setText("");
helpBuilder.setView(input);
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
Toast.makeText(CreateNote.this, "Page has been added to group", Toast.LENGTH_SHORT).show();
}
});
helpBuilder.setNeutralButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//open another alertbox
AlertDialog.Builder helpBuilder2 = new AlertDialog.Builder(CreateNote.this);
helpBuilder2.setTitle("Assign a new group");
helpBuilder2.setMessage("Create group?");
final EditText input = new EditText(CreateNote.this);
input.setSingleLine();
input.setText("");
helpBuilder2.setView(input);
helpBuilder2.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Create Group
Toast.makeText(CreateNote.this, "Group has been created", Toast.LENGTH_SHORT).show();
}
});
helpBuilder2.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog2 = helpBuilder2.create();
helpDialog2.show();
}
});
helpBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
});
Help would be greatly appreciated.
I eventually managed to solve this problem by creating two separate functions to generate each dialog box, and when one closes it calls the function to create the other one, kinda like recycling (or maybe closer to looping functions). Although, I'm not entirely sure how performance heavy this is, but it seems to do the job without any issues from what I'm testing. If anyone would like to chime in on how this could be an issue, then I'm open to hearing what others have to say about the negative points of using alert dialog boxes this way.
You can show an activity as dialog. Put this in your manifest file.
<activity android:theme="#android:style/Theme.Dialog" android:excludeFromRecents="true"/>
From this answer: Android Activity as a dialog

How do I make the AlertDialog box appear outside the app?

#Override
public void run() {
//Create thread that can alter the UI
AlarmPage.this.runOnUiThread(new Runnable() {
public void run() {
cal = Calendar.getInstance();
//See if current time matches set alarm time
if((cal.get(Calendar.HOUR_OF_DAY) == alarmTime.getCurrentHour())
&& (cal.get(Calendar.MINUTE) == alarmTime.getCurrentMinute())){
//If the sound is playing, stop it and rewind
if(sound.isPlaying()){
ShowDialog();
alarmTimer.cancel();
alarmTask.cancel();
alarmTask = new PlaySoundTask();
alarmTimer = new Timer();
alarmTimer.schedule(alarmTask, sound.getDuration(), sound.getDuration());
}
sound.start();
}
}
});
}
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT);
}
});
alertDialog.show();
}
I am making a simple alarm clock app that notifies the user. I want to make a alert box that gives the user the option to turn off the alarm when it goes off. I was able to make the alert box, but it only appears in the app not outside of the app. I understand the app has to be in the background running. If I need to show more code or be more specific, just ask please.
Add a line as:
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
// line you have to add
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
check now.
Do not accept answers if they don't address your question, it is misleading.
The accepted answer is not correct, as it will never work outside your application.
Reason:
It requires an activity context not application context.
If you provide application context, your app will crash with IllegalArgumentException- you need to use Theme.AppCompat or their decendents...
If you need functionality as actually stated in the question you have to have a separate activity themed as a Dialog like here
or you can add a custom view to your window using window manager and making it system level alert like here.
Do this create an Activity without ContentView or a View associated with it and call your alertDialog method in your onCreate also remember to set the background of the Activity to Transparent using ColourDrawable
And that activity will look like a dialog or will suit your preference, you can also fall back to Themes so you can set an Activity as Dialog and treat it like Dialog also use DialogFragment

Dialog does not get dismissed on call

builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
longOperations();
}
});
In the above code , whenever I do dialog.dismiss(), the dialog is not getting dismissed on the spot, rather, android wait for the below method finish. why ? As I want to the dialog get dismissed whenever I call it.
The issue is your longOperations() are happening on the UI thread. The dialog is not dismissed until after the onClick code is finished executing. You should move this into an AsyncTask.

Categories