I have an AlertDialog on a method and the method is used inside a Handler. When the Handler running every time the AlertDialog also loading again and again, I want to show the dialog one time if the dialog is still showing I don't want to load it again. For this I have the below code but not working.
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
checkCountry();
}
};
handler.postDelayed(runnable, 1000);
public void checkCountry() {
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogueBuilder.create();
if(alertDialog.isShowing()){
//Do Something
}else{
alertDialog.show();
}
}
Create your Dialog only once and not every time:
private AlertDialog alertDialog;
// ...
initDialog();
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(this, 1000);
checkCountry();
}
};
handler.postDelayed(runnable, 1000);
//...
public void initDialog() {
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog = alertDialogueBuilder.create();
}
public void checkCountry() {
if(alertDialog.isShowing()){
//Do Something
}else{
alertDialog.show();
}
}
To show only 1-time dialog call only this checkCountry() method from which you want to show this dialog. And, please remove the Handler code. No need to use Handler here. Use only checkCountry() method to show the dialog.
The oldest trick in the book is to just make a boolean field "isAlertDialogShown" with false initialization, upon creation to true and in the onClick set it to false again (if you want it to be shown again when the handler fires).
private boolean isShown = false;
public void checkCountry() {
if (isShown){
//do something
return;
}
isShown = true;
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
isShown = false;
finish();
}
});
AlertDialog alertDialog = alertDialogueBuilder.create();
alertDialog.show();
}
if you want to try and use the alertDialog isShowing you need to use the one you created and not the new one, so again save it as a field,
but you will still might have an edge case if the handler timer is running too fast, and that is alertDialog.show() is not an immediate operation:
AlertDialog alertDialog;
public void checkCountry() {
if ( alertDialog != null && alertDialog.isShowing){
//do something
return;
}
alertDialogueBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogueBuilder.setTitle("VPN Detected!");
alertDialogueBuilder.setMessage("Please Turn Of VPN To Continue!");
alertDialogueBuilder.setIcon(R.drawable.errorstop);
alertDialogueBuilder.setCancelable(false);
alertDialogueBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog = alertDialogueBuilder.create();
alertDialog.show();
}
Related
I'm building an app that has 2 dialogues that open up and I want something to occur if the user presses the back button while certain dialogues are open. However, for some reason, the back button event is not registering when the dialogues are open. I tested it by putting a log in onBackPressed() and whenever the dialogues are NOT open and I'm simply on the main activity, the logs appear on logcat. However, if the dialogues are open, I simply get this:
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
Below I have placed the code for the dialogues:
public void pair() {
final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
AlertDialog.Builder pairedList = new AlertDialog.Builder(this);
pairedList.setTitle("Paired Devices");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice);
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
arrayAdapter.add(device.getName());
}
}
pairedList.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.disable();
// pair_dialog = false;
}
});
pairedList.setPositiveButton("Pair New", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS), 0);
}
});
pairedList.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// connect_dialog = true;
String strName = arrayAdapter.getItem(which);
AlertDialog.Builder builderInner = new AlertDialog.Builder(MainActivity.this);
builderInner.setMessage(strName);
builderInner.setTitle("Connect To:");
builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().equals(strName)){
paired = device;
dialog.dismiss();
}
}
}
});
builderInner.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// connect_dialog = false;
pairedList.show();
}
});
builderInner.show();
}
});
pairedList.show();
// pair_dialog = true;
}
Below is my onBackPressed() method which is right after the above method. Nothing out of the ordinary, I don't think.
#Override
public void onBackPressed() {
Log.e(TAG, "Back Button Pressed");
super.onBackPressed();
}
Like I said, if the dialogues are not open, the log shows up just fine in logcat but if the dialogues are open, it's like the back button doesn't register.
this worked for me...
yuordialog.setOnKeyListener(new Dialog.OnKeyListener() {
#Override
public boolean onKey(DialogInterface arg0, int keyCode,
KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//your stuff....
}
return true;
}
});
If you have added,
dialog.setCancelable(false);
change it to,
dialog.setCancelable(true);
Actually, setCancelable(false) cancel the event of touch outside the dialog and back press also.
You can also use
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//your dismiss code here
}
});
This listens to both backpress events and dismiss by touch.
I'm coding through Deitel: Android How to program examples and in two of them my Android Studio gives warning/error on anonymous inner classes. It declares that Fragments should be static.
What's the correct way to go through this? If I make static non-anonymous inner class then there is no warning about the class, but I can't reference to non-static class variables(?). Other way could be to make a separate class (not inner class), but there is same problem with referencing variables.
This problem in with example Cannon Game, class CannonView, method showGameOverDialog (below) and also on FlagQuiz.
private void showGameOverDialog(final int messageId) {
final DialogFragment gameResult =
new DialogFragment() {
#Override
public Dialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(messageId));
builder.setMessage(getResources().getString(
R.string.result_format, shotsFired, totalElapsettime
));
builder.setPositiveButton(R.string.reset_game,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialogIsDisplayed = false;
newGame();
}
});
return builder.create();
}
};
activity.runOnUiThread(
new Runnable() {
#Override
public void run() {
showSystemBars();
dialogIsDisplayed = true;
gameResult.setCancelable(false);
gameResult.show(activity.getFragmentManager(), "results");
}
}
);
}
// display an AlertDialog when the game ends
private void showGameOverDialog(final int messageId) {
// DialogFragment to display game stats and start new game
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(getResources().getString(messageId));
// display number of shots fired and total time elapsed
builder.setMessage(getResources().getString(
R.string.results_format, shotsFired, totalElapsedTime));
builder.setPositiveButton(R.string.reset_game,
new DialogInterface.OnClickListener() {
// called when "Reset Game" Button is pressed
#Override
public void onClick(DialogInterface dialog,
int which) {
dialogIsDisplayed = false;
newGame(); // set up and start a new game
}
}
);
/* final DialogFragment gameResult =
new DialogFragment() {
// create an AlertDialog and return it
#Override
public Dialog onCreateDialog(Bundle bundle) {
// create dialog displaying String resource for messageId
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(messageId));
// display number of shots fired and total time elapsed
builder.setMessage(getResources().getString(
R.string.results_format, shotsFired, totalElapsedTime));
builder.setPositiveButton(R.string.reset_game,
new DialogInterface.OnClickListener() {
// called when "Reset Game" Button is pressed
#Override
public void onClick(DialogInterface dialog,
int which) {
dialogIsDisplayed = false;
newGame(); // set up and start a new game
}
}
);
return builder.create(); // return the AlertDialog
}
};
*/
// in GUI thread, use FragmentManager to display the DialogFragment
activity.runOnUiThread(
new Runnable() {
public void run() {
final AlertDialog gameResult = builder.create();
showSystemBars();
dialogIsDisplayed = true;
gameResult.setCancelable(false); // modal dialog
// gameResult.show(activity.getFragmentManager(), "results");
gameResult.show();
}
}
);
}
I wrote the below code in Android. The function "confirmalert" actually displays an alert box and has positive and negative buttons.
But always the "else" part is working, that too even if I haven't selected anything.
Please reply with how to make it work properly.
private void updatestockin()
{
if(confirmalert())
{
Toast t = Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_SHORT);
t.show();
}
else
{
Toast t = Toast.makeText(getApplicationContext(), "User Rejected", Toast.LENGTH_SHORT);
t.show();
}
}
My confirmalert function:
public boolean confirmalert(String title,String msg)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(msg);
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
flag=true;
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
flag=false;
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return flag;
}
The confirmalert() method returns immediately (before the AlertDialog is even displayed on screen) with the value of the flag field which is false if not set otherwise in your class. That happens because AlertDialog.show() is asynchronous, otherwise it would block the main (ui) thread and you would not be able to interact with the app any longer after calling it.
What you need to do is move the call to confirmalert() outside of updatestockin() method and call updatestockin from the Dialog.OnClickListener().
//call this from where you normally call updatestockin()
confirmalert();
//updatestockin(); // comment this call as it will happen after the user clicks one of the AlertDialog buttons
private void updatestockin(boolean flag) {
if (flag) {
Toast t = Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_SHORT);
t.show();
} else {
Toast t = Toast.makeText(getApplicationContext(), "User Rejected", Toast.LENGTH_SHORT);
t.show();
}
}
public boolean confirmalert(String title,String msg)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(msg);
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
updatestockin(true);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
updatestockin(false);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return flag;
}
I think there is an async issue. So maybe this alert in different thread. So since your flag is initialized false, it runs that.
So using wait() and notify() you can sync the threads
Try this:
public boolean confirmalert(String title,String msg)
{
wait();
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage(msg);
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
flag=true;
notify();
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
flag=false;
notify();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
wait();
return flag;
}
It should work. not tested. If possible read about wait and notify a bit to properly understand, hope it takes you to right path.
Here I want to show two dialog boxes...one for if there is net connection available and other if there is no connection..but i want that when one dialog box is shown, the other dialogue box should be dismissed .......dismiss() is not working in this case....and somehow if I use AlertDialog instead of AlertDialog.Builder to use dismiss(), then i am not able give setPositive, setNegative and setNeutral buttons....any help will be appreciated.......
BroadcastReceiver br;
#Override
protected void onCreate(Bundle savedInstanceState) {
...........//
getStarted();
}
private void getStarted() {
if (br == null) {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
...............//
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.show();
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("No Internet ");
builder.setMessage("Offline");
builder.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder.show();
}
}
};
final IntentFilter if = new IntentFilter();
if.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(br, if);
}
}
}
Dismiss Your dialog if NetworkInfo.State.CONNECTED is connected,Please change builder1.show(); into builder1.dismiss();
if (state == NetworkInfo.State.CONNECTED) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setCancelable(false);
builder1.setTitle("Connected");
builder1.setMessage("Online");
builder1.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
});
builder1.dismiss();
}
Use broadcast receiver to react when the connection is changed with intent filter android.net.ConnectivityManager.CONNECTIVITY_ACTION. So, you can do your stuffs when the receiver receive the intent (or there connection is changed). See here.
I'm working on an accesibility app. When the user wants to leave the app I show a dialog where he has to confirm he wants to leave, if he doesn't confirm after 5 seconds the dialog should close automatically (since the user probably opened it accidentally). This is similar to what happens on Windows when you change the screen resolution (an alert appears and if you don't confirm it, it reverts to the previous configuration).
This is how I show the dialog:
AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
exitLauncher();
}
});
dialog.create().show();
How can I close the dialog 5 seconds after showing it?
final AlertDialog.Builder dialog = new AlertDialog.Builder(this).setTitle("Leaving launcher").setMessage("Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
exitLauncher();
}
});
final AlertDialog alert = dialog.create();
alert.show();
// Hide after some seconds
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
if (alert.isShowing()) {
alert.dismiss();
}
}
};
alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
handler.removeCallbacks(runnable);
}
});
handler.postDelayed(runnable, 10000);
Use CountDownTimer to achieve.
final AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle("Leaving launcher").setMessage(
"Are you sure you want to leave the launcher?");
dialog.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
exitLauncher();
}
});
final AlertDialog alert = dialog.create();
alert.show();
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
alert.dismiss();
}
}.start();
Late, but I thought this might be useful for anyone using RxJava in their application.
RxJava comes with an operator called .timer() which will create an Observable which will fire onNext() only once after a given duration of time and then call onComplete(). This is very useful and avoids having to create a Handler or Runnable.
More information on this operator can be found in the ReactiveX Documentation
// Wait afterDelay milliseconds before triggering call
Subscription subscription = Observable
.timer(5000, TimeUnit.MILLISECONDS) // 5000ms = 5s
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Long>() {
#Override
public void call(Long aLong) {
// Remove your AlertDialog here
}
});
You can cancel behavior triggered by the timer by unsubscribing from the observable on a button click. So if the user manually closes the alert, call subscription.unsubscribe() and it has the effect of canceling the timer.
This is the code, refer this link:
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get button
Button btnShow = (Button)findViewById(R.id.showdialog);
btnShow.setOnClickListener(new View.OnClickListener() {
//on click listener
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setTitle("How to close alertdialog programmatically");
builder.setMessage("5 second dialog will close automatically");
builder.setCancelable(true);
final AlertDialog closedialog= builder.create();
closedialog.show();
final Timer timer2 = new Timer();
timer2.schedule(new TimerTask() {
public void run() {
closedialog.dismiss();
timer2.cancel(); //this will cancel the timer of the system
}
}, 5000); // the timer will count 5 seconds....
}
});
}
}
HAPPY CODING!
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.game_message);
game_message = builder.create();
game_message.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
game_message.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 5000);
Reference : https://xjaphx.wordpress.com/2011/07/13/auto-close-dialog-after-a-specific-time/
For Kotlin inspired by Tahirhan's answer.
This is what worked for my current project. Hope it will help someone else in the near future.
Im calling this function in a fragment. Happy coding!
fun showAlert(message: String) {
val builder = AlertDialog.Builder(activity)
builder.setMessage(message)
val alert = builder.create()
alert.show()
val timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
alert.dismiss()
timer.cancel()
}
}, 5000)
}
I added automatic dismiss with the time remaining shown in the positive button text to an AlertDialog.
AlertDialog dialog = new AlertDialog.Builder(getContext())
.setTitle(R.string.display_locked_title)
.setMessage(R.string.display_locked_message)
.setPositiveButton(R.string.button_dismiss, null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
final Button positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
final CharSequence positiveButtonText = positiveButton.getText();
new CountDownTimer(AUTO_DISMISS_MILLIS, 100) {
#Override
public void onTick(long millisUntilFinished) {
positiveButton.setText(String.format(Locale.getDefault(), "%s (%d)",
positiveButtonText,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1));
}
#Override
public void onFinish() {
dismiss();
}
}.start();
}
});
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text("Sucess"),
);
});
Timer(Duration(seconds: 2),()=>Navigator.pop(context));
Create a dialog and find a button.
AlertDialog.Builder builder = new AlertDialog.Builder(this).setPositiveButton( android.R.string.ok, null );
final AlertDialog dialog = builder.create();
dialog.show();
View view = dialog.getButton( AlertDialog.BUTTON_POSITIVE );
If you use a custom view for dialog just use it. Next step.
view.postDelayed( new Runnable(){
#Override
public void run(){
dialog.cancel(); // no problem if a user close it manually
}
}, 5000 );
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
then call dismiss meth it work
alertDialog .dismiss();