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();
Related
By using the retrofit as REST Client,
private void doGetRestBagLotNumber(int bagNumber, String lotNumber, final BagLotNumberRestService callback) {
Call<BagLotNumberModel> call = bagLotNumberRestService.getAntamBagLotNumber(bagNumber, lotNumber);
call.enqueue(new Callback<BagLotNumberModel>() {
#Override
public void onResponse(Call<BagLotNumberModel> call, Response<BagLotNumberModel> response) {
if (response.code() == 404 || response.code() == 422) {
Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
} else {
int id = response.body().getId();
int bagNumber = response.body().getBagNumber();
String lotNumber = response.body().getLotNumber();
// Adding the response to recylerview
preparedObjectDataBagLotNumber(id, bagNumber, lotNumber);
callback.onSuccess(response.body() != null);
}
}
#Override
public void onFailure(Call<BagLotNumberModel> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I have a method to display a dialog that contains several edit text
to input data from the user.
Here's the code.
private void addItemTextMethod() {
// get prompts.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts_antam_incoming, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to alertDialog builder
alertDialogBuilder.setView(promptsView);
final EditText bagNumber = (EditText) promptsView.findViewById(R.id.editTextDialogAntamBagNumber);
final EditText lotNumber = (EditText) promptsView.findViewById(R.id.editTextDialogLotNumber);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("Search", null)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button button = ((AlertDialog) alertDialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(view -> {
doGetRestBagLotNumber(
Integer.parseInt(bagNumber.getText().toString()), lotNumber.getText().toString(),
new BagLotNumberRestService() {
#Override
public void onSuccess(boolean value) {
if($value){
// The question is here
// Show Big Thick in center of dialog
// Show bottom option, Close or Adding More
// If user choose Adding More , display this dialog again
}
}
#Override
public Call<BagLotNumberModel> getAntamBagLotNumber(int bagNumber, String lotNumber) {
return null;
}
}
);
});
}
});
alertDialog.show();
}
How when the result of the doGetRestBagLotNumber callback is true,
the app show option like this:
Show Big Thick in center of dialog as Success message
Show bottom option, Close or Adding More.
If user choose Adding More , display this dialog again
Any help it so appreciated
Use the instance of your inflated view to change the child views inside it. For example use this inside your onSuccess method:
((ImageView)promptsView.findViewById(R.id.tickIndicationView)).setImageResource(R.drawable.ic_tick);
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();
}
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 try to launch a progressbar in my application but wehn I launch it the BAr isn't show before the function is started
public void onClick(View v) {
if (v == button)
{
ProgressDialog dialog = ProgressDialog.show(App.this, "",
"Loading. Please wait...", true);
dialog.show();
try
{
directory = edittext.getText().toString();
FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/folder.db");
BufferedWriter out = new BufferedWriter(fstream);
out.write(directory);
//Close the output stream
out.close();
if(hide_or_show == "hide")
{
edittext.setVisibility(View.INVISIBLE);
folder_to_hide.setVisibility(View.INVISIBLE);
hide();
dialog.dismiss();
}
else
{
show();
edittext.setVisibility(View.VISIBLE);
folder_to_hide.setVisibility(View.VISIBLE);
dialog.dismiss();
}
}
catch(Exception x)
{
String ErrorMessage = x.getMessage();
Toast.makeText(this,"Error"+ErrorMessage, Toast.LENGTH_LONG).show();
finish();
}
}
if (v == options)
{
final CharSequence[] items = {"Change password", "http://www.alexander-fuchs.net/", "Market"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Options");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item] == "Change password")
{
createpass();
}
if (items[item] == "http://www.alexander-fuchs.net/")
{
intentstarter(items[item].toString());
toaster(items[item].toString());
}
if (items[item] == "Market")
{
intentstarter("market://search?q=pub:Alexander Fuchs");
toaster("Please wait...");
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
when I tap the button it takes long to respond and then the whole function finishs without prompting an progressbar
onClickis a callback where the return to Android is only returned when the callback ends.
All UI interaction you do basically is collected and queued while the callback is active and executed after return (may not technically totally accurate).
For you ProgressBar to show up at the start of the action and vanish at the end, you can implement an AsyncTask where the progress bar is shown in onPreExecute, the real computation is done in doInBackground and the progressbar is dismissed in onPostExecute. For example:
protected void onPreExecute() {
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.show();
}
protected void onPostExecute(Map<Integer, String> integerStringMap) {
if (dialog!=null)
dialog.cancel();
}
protected void onProgressUpdate(Integer... values) {
int val = values[0]*10000/num;
dialog.setProgress(val);
}
See here for the more complete example.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window — token null is not for an application"
I've tried different things, but I still keep the same error:
android.view.WindowManager$BadTokenException: Unable to add window
At this line:
alertDialog.show();
Can you look at the code?
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
Context mContext = this;
alertDialog = new AlertDialog.Builder(mContext).create();
LoadData();
}
public void LoadData()
{
Thread t1 = new Thread(this);
t1.start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if(!rssItems.isEmpty())
{
switch (msg.what) {
case STOPSPLASH:
//remove SplashScreen from view
//splash.setVisibility(View.GONE);
Intent intent = new Intent(
"news.displayNews");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NewsDisplayer.rssItems.clear();
NewsDisplayer.rssItems.addAll(rssItems);
startActivity(intent);
Close();
break;
}
}
else
{
alertDialog.setCancelable(false); // This blocks the 'BACK' button
alertDialog.setMessage("No connection.");
alertDialog.setTitle("Error...");
alertDialog.setButton("Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
LoadData();
}
});
alertDialog.setButton2("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
System.exit(0);
}
});
alertDialog.show();
}
}
};
This is because the context you are using to create the alertDialog doesn't support it. So instead of mContext, try getParent() or getApplicationContext(). That might work.
I think that's because you're running this in a thread. alertDialog.show(); has to be executed on the UI thread. Try using an AsyncTask instead.
EDIT: my bad, I didn't read carefully the code.