AlertDialog OnClose Event Android - java

I have been looking around and I couldn't find anything, so I don't know if its possible, but is there a way to do something on close for alertdialogs?
In my situation, I have the background UI paused while the dialog is up as its a pause screen. If you click the buttons in the dialog it will run the onClick stuff, so I have it unpausing there, but if they click off of the dialog it closes the dialog but doesn't run onClick. Is there anyway to get something to run when they click off to the side? Thanks!

You can set an onDismissListener() to listen whenever the dialog goes away. Docs.

You can use onDismissListener() but it was introduced in higher APIs so will not be compatible with older ones. You can use onCancel() instead.
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("My Titile");
alertDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
//your logic
}
});

The only way to do this is to not use a AlertDialog.Builder and instead create a PopupWindow sub class.
A good example may be found here on line 37 :
https://github.com/lorensiuswlt/NewQuickAction/blob/master/src/net/londatiga/android/PopupWindows.java

You can use setCanceledOnTouchOutside(false) to force the user to click on the cancel button.
You could also (if you're using a DialogFragment) override the onDetach() method.
And finally you could set a dismiss listener.

Related

Perform an Action on showing AlertDialoge, then dismiss

I would like to start an AlertDialogue showing a loading message and a ProgressBar icon, then on showing the dialogue I would run the heavy processing with the ProgressBar spinning, and finally cancel the dialogue when the processing is over.
I have tried putting the logic on setOnShowListener of the alert dialogue which was not carried out. Then, I have tried starting the dialogue then using a delayed handler like the following:
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
// heavy procssing logic
// alert.dismiss();
}
}, 1000);
Though, the ProgressBar icon stopped spinning, so I assumed that my heavy processing blocked the UI. How do I achieve what I need. Thanks.
Edit: I have replaced the handler with new Thread() and everything worked properly. Would this approach cause any problems like memory leaks?
Create a new AsyncTask to do your work, this will cause any code placed in the “doInBackground()” method to be ran in a background thread, you have pre-execute and post-execute to run code on the main thread, my recommendation is create an alertDialog in the pre-execute methods and close it on the post-execute, using “publishProgress()” method In the doInBackground method to update your dialog as you need.
Otherwise instead of an alertDialog (or as well as) you can use a progressBar, simply have it in the view preciously, instantiate it as you normally would.
<ProgressBar
android:id=“+id/progressBar”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:centreInParent=true
android:indeterminate=true
android:visibility=gone />
ProgressBar progressBar = view.findViewById(R.id.progressBar)
Now when you want to show the progress bar use
progressBar.setVisibility(visible)
Or to hide
progressBar.setVisibility(gone)

Cannot dismiss 2 AlertDialogs at once in Android

I've built an android AlertDialog (named dialog) that fires other Android AlertDialog (named dialog2) if some conditions happen.
I've checked that what if only one of them is displayed on screen it is dismissed without any problem.
Problem comes when both of them are showing, that happens when I press the OK button for the second dialog, it just closes the second dialog, despite the first dialog is even showing on screen.
This is the code related to dialog2 for that operation:
dialog2.setOnShowListener(new DialogInterface.OnShowListener()
{
#Override
public void onShow(final DialogInterface dialog)
{
Button button = ((AlertDialog)
dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
[some more operations]
dialog2.dismiss();
dialog.dismiss();
}
});
}
});
The strangest thing is that if I supress the line dialog2.dismiss(); by leaving only dialog.dismiss(); what get dismissed is the second dialog, not the first one, looks like android somehow confuses one with the other, and I don't think that should be happening because they are created separately like this:
dialog=[code to create that dialog]
dialog2=[code to create that dialog]
Doing that the only way I see that app would close dialog2 when asked to close dialog would be doing dialog=dialog2, which I am not. I think They should be different objects loaded in memory each one with their characteristics.
I don't see any reason of why this is happening, seems like a clueless error from my point of view. Hope you can give ideas about what is happening.
A couple things to take note of here:
First, it isn't necessary to create an "onShowListener", unless you actually need to perform a task when the dialog is shown, this code should help you correctly create an AlertDialog:
new AlertDialog.Builder(getContext())
.setTitle(R.id.dialog_title)
.setMessage(R.id.dialog_message)
.setPositiveButton(R.id.positive_text, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//do onClick stuff here
}
})
.show();
This example does all your setup at once. If you need a reference to this dialog or don't want to show it right away, just use AlertDialog.Builder dialog1 = new ..., and then use dialog1.show() to create the dialog.
Second, the reason that only the second dialog is closing when you suppress dialog2.dismiss() is because there is a local variable named 'dialog' inside of your onShow() method (look at the method parameters) that is taking precedence over your broader scoped 'dialog' variable.
Third, to answer your actual question, can you dismiss the first dialog just before you show the second? I don't see any real reason to have 2 dialogs open at the same time.

Clicking button in AlertDialog made in onOptionsItemSelected crashes emulator

My main question is: Is there anyway I can get trigger an AlertDialog from inside onOptionsItemSelected() without it crashing my emulator when I press a button on the dialog?
I have looked all over the internet for this but everyone I find keeps saying the same thing but even when I copy and paste their code I get the same error. So I'll try explain my situation as well as I can.
Here is an example of a pretty simple AlertDialog:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this)
.setTitle("Your Title")
.setMessage("Click yes to exit!")
.setCancelable(false)
.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Now this WORKS. As long as I run it OUTSIDE of the onOptionsItemSelected() function. For example, if I add this piece of code inside the onClickListener for a regular Button. Then the alert dialog will appear when I click the button and everything will work. However when I include this piece of code inside my onOptionsItemSelected(). Then the alert dialog will appear, but pressing a button on the dialog will crash my entire emulator. Here is my onOptionsItemSelected():
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_trash:
Log.i("trash", "button clicked");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this)
.setTitle("Your Title")
.setMessage("Click yes to exit!")
.setCancelable(false)
.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return true;
case R.id.action_help:
Log.i("help", "button clicked");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Now when I click on the item in my toolbar linked with the action_trash id. I get an alert dialog, but when I click the OK button, my entire android emulator just crashes. And the only warning I can still see is this:
Hax is enabled
Hax ram_size 0x40000000
HAX is working and emulator runs in fast virt mode.
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
EmuGL:WARNING: bad generic pointer 0x7fc16d378600
Which I am pretty sure is an unrelated message. I sometimes see people asking for LogCats, but there are none that I can find since the entire emulator has crashed.
And as a side question: why doesn't this even work at all? Is it because the onClickListener() made inside setNeutralButton() has somehow been destroyed? I am fairly new to android, so if this is some big nooby mistake that can be avoided in the future any advice would be appreciated.
P.S. I have also tried replacing '.Builder(this)' with '.Builder(MainActivity.this)' and all the variations I have encountered so far and none of them solve the issue.
Thanks in advance :)
I've ran into this same thing. Two separate things worked for me.
Changing the AVD settings to have "Software - GLES 2.0" instead of hardware or auto for the "Emulated Performance" option.
Turn on "Show Layout Bounds" in the developer options of the AVD.
Either of those should fix the issue, you don't need to do both.

Pause Android app-flow

When a return button is pressed in the app I am working on:
public void clickReturn(View view)
{
// ...
// Call an event handler before finishing the activity
_appData.CustomDetail.hookBeforeFinish(this, new ArrayList<CompSubmission>(_submissions));
// Finish this activity
finish();
}
I am not able to modify clickReturn() - the way the application is structured, all I have access to is the hook hookBeforeFinish().
What I want to do is add a dialog to prompt for some input. I can do this in hookBeforeFinish(), but it only appears for a split second. I assume what is happening is I set up the AlertDialog builder, call builder.show() but finish() is being called directly afterwards - so the dialog only appears momentarily.
Is there anything I can put after builder.show() in the hook function such that it won't continue execution to finish()? If I can pause the application flow until someone presses the OK button on the dialog thatwould work better for me.
Thanks
Please comment finish().
Then read and add a dialog as explained here. In your positive button click (e.g. OK button), add finish();
Edit
Since you cannot override clickReturn() or change the class, you can use your hookBeforeFinish() to create a dialog and comment 'clickReturn();' line.
In your dialog, in the listener for the button which expects to finish the activity add clickReturn();.
This way you will pause the activity closing until user decides to do so.

The buttons in my android application are unresponsive

I am trying to implement a dialog box that pops up when a button is pressed by the user. This currently works, however the buttons I have included in the pop up are unresponsive. I have tried the following code to try and resolve the problem.
public void showDialog()
{
final Dialog dialog= new Dialog(context);
dialog.setContentView(R.layout.dialog_info);
infoView=(EditText) dialog.findViewById(R.id.infoView);
infoView.setFocusable(false);
infoView.setText("");
dialog.setTitle(aList.get(count).toTitle());
infoView.append(aList.get(count).toDescription());
Button back=(Button)findViewById(R.id.back);
Button reminder=(Button)findViewById(R.id.reminder);
Log.e(TAG,"Testing click 1.5");
back.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e(TAG,"Testing click 2");
dialog.dismiss();
}
});
dialog.show();
}
showDialog() gets called after a button (back) in the first view is pressed
public void onClick(View v) {
for (count =0;count<aList.size();count++)
{
if (v==buttons.get(count))
{
Log.e(TAG,"Testing click -1.1");
showDialog();
}
}
}
Correct me if I understood wrong,
your button back and reminder are a part of the dialog, so you should be getting a null pointer exception. Try finding your buttons like this
Button back=(Button)dialog.findViewById(R.id.back);
Button reminder=(Button)dialog.findViewById(R.id.reminder);
EDIT: By doing this you'll find the button inside the dialog. If you don't do this android will try to find the button in Activity itself and not the dialog .
For the Override problem please recheck that you've done the right import. (there are two kinds of import for View.onClickListner I don't remember their name right now.) You can delete your import associated with View.Onclick and try to re-import the correct package.
If this is not the case then I might have misinterpreted your question. You can check your Java Compliance level and see if its on 1.6 or not. You can check this by going to your project properties under Java Compliance Level
What version of Java are you using?
Right-click your project
Go to Properties
Go to Java Compiler
Enable project specific settings
Select 1.6 for Java compliance level
This will fix the #Override errors. If you want to use another version, you can just remove all #Override annotations.

Categories