Deitel How to program Android Cannon Game anonymous inner class warning - java

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();
}
}
);
}

Related

How can I stop same alert dialog showing every time from handler?

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();
}

Use method to create multiple AlertDialog with varying behavior

I have an activity with several buttons. I want each button to open an AlertDialog to confirm the user's action before continuing. I am looking for a way to create a method that will set up the AlertDialog, pass in a string for the title and message, and then pass a result back to the activity so I can have it select what action to do. I have looked around and not been able to find a way to pass a result back to the activity, but the if statement to check the result runs before the user clicks the dialog's button.
Here is what I have so far in Activity.java:
#Override
public void onClick(View v) {
String title, message;
switch (v.getId()) {
case R.id.settings_btn_cleardatabase:
title = getResources().getString(R.string.settings_dialog_clearstats_title);
message = getResources().getString(R.string.settings_dialog_clearstats_text);
showDialog(title, message);
// This is the part that gets bypassed before user clicks dialog button
if (mResultCode == RESULT_OK) {
Toast.makeText(SettingsActivity.this, "Player Scores Cleared", Toast.LENGTH_SHORT).show();
}
break;
case R.id.settings_btn_cleargaminggroup:
title = getResources().getString(R.string.settings_dialog_cleargroup_title);
message = getResources().getString(R.string.settings_dialog_cleargroup_text);
showDialog(title, message);
if (mResultCode == RESULT_OK) {
Toast.makeText(SettingsActivity.this, "Gaming Group Cleared", Toast.LENGTH_SHORT).show();
}
break;
}
}
Generic Alert Method:
private void showDialog(String title, String message) {
AlertDialog.Builder clearStatsDialogBuilder = new AlertDialog.Builder(this);
// Sets title
clearStatsDialogBuilder.setTitle(title);
// Sets message
clearStatsDialogBuilder
.setMessage(message)
.setIcon(R.drawable.ic_warning_white_24dp)
.setCancelable(false)
.setPositiveButton(R.string.settings_dialog_clear_confirmbtn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mResultCode = RESULT_OK;
}
})
.setNegativeButton(R.string.settings_dialog_clear_cancelbtn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mResultCode = RESULT_CANCELED;
dialog.cancel();
}
});
// Create alert dialog
AlertDialog clearStatsDialog = clearStatsDialogBuilder.create();
// Show it
clearStatsDialog.show();
}
Did you try this ?
create your DialogFragment and define an interface that the Activity will implement
Then in the DialogFragment when you want to return the result to the Activity you cast the activity to the interface
In the Activity you implement that interface and get the values
example :
//////////// 1 stage
public interface DialogFragmentListener {
public void onReturnValue(String reurnValue);
}
/////////////////////////// 2 stage
#Override
public void onClick(DialogInterface dialog, int id) {
DialogFragmentListener activityDL = (DialogFragmentListener) getActivity();
activityDL.onReturnValue("Pass the value");
}
/////////////////////////////// 3 stage
public class MyActivity implements DialogFragmentListener {
...
#Override
public void onReturnValue(String returnVal) {
Log.d("onReturnValue", "Got value " + returnVal+ " back from Dialog!");
}
}
refer ->Using DialogFragments

Remember what was selected in single choice AlertDialog

I have an AlertDialog which displays an array into a single selected choice:
protected boolean blFrom, blTo;
protected void showSelectToDialog() {
boolean[] checkedDate = new boolean[toDate.length];
int count = toDate.length;
DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Auto-generated method stub
onChangeSelectedTo(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select To Year");
builder.setSingleChoiceItems(toDate, count, setD2);
builder.setCancelable(true);
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog2 = builder.create();
dialog2.show();
}
protected void onChangeSelectedTo(int j) {
bTo.setText(toDate[j]);
sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
blTo = true;
displayToast(String.valueOf(sTo));
to = j;
dialog.dismiss();
}
What I want to do is the first time it loads it should display the default. Once I select a choice and the dialog closes and I bring up the same dialog again it should show the previously selected choice I made and scroll to it.
How do I accomplish it?
As of right now, I can get the selected position but what next?
You can store the chosen value in a variable of your Activity or using SharedPreferences

How to force user to deal with dialog before allowing access to activity? AND What's wrong with my licensing code?

Ok so I recently completed an android app - my first one :D! - and because it is a paid app Google tells me I have to add the licensing stuff. That's fine and dandy, except I've been getting mind f*cked by it for the past five hours. Finally think I understand it a little and got it going, but in testing it in my emulator I come up with two issues:
I'm using the google API for 4.1, as instructed by their handy how-to on the developer console, but nomatter what I always end up coming up with my Connection Error dialog. Code here:
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
And cooresponding dialog being called:
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
My first question: How come it isn't connecting to the server as it should be? I've constructed my testing apratus as instructed by their tutorial. I've gone over it three times!
Second question: When I do launch the app on the emulator, the Connection Error dialog shows up fine. I hit retry, and it works. I hit Cancel, and it kills the app. However, if I simply click anywhere else in the window, outside the dialog, it closes the dialog and the app works normally. That kindof defeats the whole purpose, eh? How do I make that... not so?
Just in case I'm an idiot and the error lies elsewhere, here's the whole class:
private static final int DIALOG_RETRY = 10;
private static final int DIALOG_ERROR=20;
private static final byte[] SALT = {1,2,3,4,5,6,72,88,-37,-55,-23,34,22,14,15,16,17,18,19,-20};
private static final String BASE64_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqvh1xrNmvio909T06vAUxW3rtc98E3xNLA6qR/zdq2zHNW tQUJkDmJGukrkWj4Vd38NiD+nW92MX3HY2/dfw4AIcwS2oyeYceYc3hi4y2KeVL84y3DrOO0fCKNqBr6/Ve0cefN9HVyy57Psl4B0y8OaG9500xuEUeguO+PyIAMqFrtHVyi/seimnrcYLTYJo9IfGTRhcwi6QqQE8OlplidaT+uYwR4hNfcNLbnWnr7xDeG5gL2usibFPg+cvhFVhIGKO/aFuAVUIH2Yoarudc888X3/ZjTbmYAGuGhS8GRxiHhTVknCznX3BcxBJNeMA+xPTZ4OnaryRkHVvoJx5WQIDAQAB";
private LicenseCheckerCallback checkerCB;
private LicenseChecker checker;
TextView title, description, cure;
ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//LICENSING
checkerCB = new CallBack();
final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
checker = new LicenseChecker(
this, new ServerManagedPolicy(this,
new AESObfuscator(SALT, getPackageName(),tm.getDeviceId())),
BASE64_PUBLIC_KEY);
checker.checkAccess(checkerCB);
//END LICENSING
setContentView(R.layout.activity_main);
title = (TextView)findViewById(R.id.title);
description = (TextView)findViewById(R.id.description);
image = (ImageView)findViewById(R.id.image);
cure =(TextView)findViewById(R.id.cure);
Spinner dropdown = (Spinner)findViewById(R.id.mainMenu);
//List Menu Items
final String options[] = {
//TURF DISEASES
"-Turf Diseases-", "Dollar Spot","Red Thread","Pythium Blight", "Necrotic Ring","Summer Patch","Brown Patch","Fairy Ring"
,"White Patch","Rust"
//TURF INSECTS
,"-Turf Insects-","Chinch Bug","Army Worm","Hunting Billbug","Aphid","Black Cutworm","Leaf Hopper","White Grub"
//ORNAMENTAL DISEASES
,"-Ornamental Diseases-","Powdery Mildew","Leaf Spot"
//ORNAMENTAL INSECTS
,"-Ornamental Insects-","Aphid","Leaf Miner","Japanese Beatle","Spider Mites","White Fly","Euonymus Scale","Web Worm"
};
//End List Menu Items
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,options);
dropdown.setAdapter(adapter);
dropdown.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
newSelection(options[position]);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void newSelection(String selection){
if(!selection.contains("-")){
title.setText(selection);
selection=selection.replace(" ", "_");
selection=selection.toUpperCase();
description.setText(getResourceID("DESC_"+selection, R.string.class));
image.setImageResource(getResourceID(selection.toLowerCase(), R.drawable.class));
}else{
title.setText("Select a disease or insect.");
description.setText("");
cure.setText("");
image.setImageResource(getResourceID("logo", R.drawable.class));
}
}
#SuppressWarnings("rawtypes")
public int getResourceID(String name, Class resType){
try{
Class res = null;
if(resType == R.drawable.class)
res=R.drawable.class;
if(resType==R.id.class)
res=R.id.class;
if(resType==R.string.class)
res=R.string.class;
java.lang.reflect.Field field = res.getField(name);
int retID = field.getInt(null);
return retID;
}catch(Exception e){
}return 0;
}
protected void onResume() {
newSelection("-");
super.onPause();
}
protected void onDestroy(){
super.onDestroy();
checker.onDestroy();
}
//LICENSING CALLBACK CLASS
private class CallBack implements LicenseCheckerCallback{
public void allow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Granted");
}
public void dontAllow(int reason) {
if(isFinishing()){
return;
}
displayResults("Access Denied");
if(reason==Policy.RETRY){
showDialog(DIALOG_RETRY);
}else{
showDialog(DIALOG_ERROR);
}
}
public void applicationError(int errorCode) {
dontAllow(0);
}
public void displayResults(String result){
}
}
//DIALOG CLASS AND ACTION LISTENERS
protected Dialog onCreateDialog(int id){
switch(id){
case DIALOG_RETRY:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
break;
case DIALOG_ERROR:
Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Would you like to purchase Landscape ID! ?");
builder1.setCancelable(true);
builder1.setPositiveButton("Yes!", new BuyOnClickListener());
builder1.setNegativeButton("No.", new CancelOnClickListener());
AlertDialog dialog1 = builder1.create();
dialog1.show();
break;
}
return super.onCreateDialog(id);
}
private final class RetryOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
checker.checkAccess(checkerCB);
}
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
onDestroy();
finish();
}
}
private final class BuyOnClickListener implements
DialogInterface.OnClickListener{
public void onClick(DialogInterface dialog, int which) {
Intent open = new Intent(Intent.ACTION_VIEW);
open.setData(Uri.parse("market://details? id=com.mustaroenterprise.landscapeid"));
startActivity(open);
}
}
}
For your second question, I would set setCanceledOnTouchOutside to false like so:
Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Connection Error: Retry?");
builder.setCancelable(true);
builder.setPositiveButton("Retry", new RetryOnClickListener());
builder.setNegativeButton("Cancel", new CancelOnClickListener());
AlertDialog dialog = builder.create();
//Add this
dialog.setCanceledOnTouchOutside(false);
dialog.show();

Android close dialog after 5 seconds?

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();

Categories