Android Progressbar starts at the wrong time - java

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.

Related

Android Studio, How to change dynamically view in dialog, case: Retrofit onSuccess

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

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

Android returning NullPointerException when asking findViewById after app is paused

whenever I use the app switcher or the app gets paused in any other way then upon resuming it I will get a NullPointerException when trying to use findViewById in my fragment. The same happens when trying to use getActivity() or anything related to the Main activity. I've tried checking of the fragment is attached or not with isAdded() and it returns true but still gives the error. (Don't mind the way the code looks, I still need to clean it up)
All irrelevant classes and methods are not included (ex. Profanity class).
MainActivity onStart method (Launch activity)
#Override
public void onStart() {
super.onStart();
Profanity.downloadList();
if (AskForPermissions()) {
if (mAuth.getCurrentUser() != null) {
mAuth.getCurrentUser().reload().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new HomeFragment()).commit();
}
});
} else {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.MainFragment, new LoginFragment()).commit();
}
} else {
onStart();
}
}
HomeFragment (The one that crashes, crash happens under Started() on the 4th line)
#SuppressWarnings("all")
#Override
public void onStart() {
super.onStart();
loadVariables();
final String UUID = ((MainActivity) getActivity()).mAuth.getCurrentUser().getUid();
User.UUID = UUID;
if (User.userName == null || User.userName.equals("")) {
Functions.loadUserData(UUID).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.getResult() == null) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose your username");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
if (input.getText().toString().toCharArray().length > 16) {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Your username must be maximum 16 characters.");
dialog.show();
} else if (Profanity.contains(input.getText().toString())) {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Please refrain from using restricted words in your username.");
input.setText("");
dialog.show();
} else {
User.userName = input.getText().toString();
dialog.dismiss();
FirebaseReferences.users.child(User.UUID).child("name").setValue(User.userName);
Functions.showBottomMessage(getView(), "Username saved.");
}
} else {
dialog.dismiss();
Functions.showBottomMessage(getView(), "Please enter a valid username.");
dialog.show();
}
}
});
Started();
} else {
HashMap temp = (HashMap) task.getResult();
if (temp.containsKey("name")) {
User.userName = temp.get("name").toString();
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose your username");
final EditText input = new EditText(getActivity());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
final AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (input.getText() != null && !input.getText().toString().equals("") && !input.getText().toString().equals(" ")) {
User.userName = input.getText().toString();
dialog.dismiss();
FirebaseReferences.users.child(UUID).child("name").setValue(input.getText().toString());
} else {
dialog.dismiss();
dialog.show();
}
}
});
}
if (temp.containsKey("place")) {
User.place = temp.get("place").toString();
}
if (temp.containsKey("ratedImages")) {
User.ratedImages = (ArrayList<String>) temp.get("ratedImages");
}
if (temp.containsKey("developer")) {
if (Boolean.valueOf(temp.get("developer").toString().toLowerCase()))
User.isDeveloper = true;
}
Started();
}
}
});
} else {
Started();
}
}
#SuppressWarnings("all")
private void Started() {
mainImageProgressBar.setVisibility(View.VISIBLE);
secondaryImageProgressBar.setVisibility(View.VISIBLE);
CacheHandler.update(getActivity(), imageView, secondImageView, true);
/*THIS IS THE FIRST CRASH POINT - */getView().findViewById(R.id.fabSendImage).setOnClickListener(getBtnSendImageOnClickListener());
getView().findViewById(R.id.btnReportImage).setOnClickListener(btnReportImageOnClick);
}
All view related code must be moved on to onCreateView(). So just place your code to onCreateView in case of fragment and onCreate in case of activity.
For more info just go through https://developer.android.com/guide/components/fragments.html
Crashing because of getView(). Because its not able get the view.
You need to pass the view which hold the view with id R.id.fabSendImage and try calling the view.findViewById(R.id.fabSendImage) to initialize.

OnclickListener not working on small screen sizes?

So I have some code that sets an onClickListener for a button that doesn't seem to work on devices with screen sizes less than 4 inches, but only for specific buttons. I'm not sure why, because it doesn't seem to be an effect OS Level version, but only screen size.
I have logging code in the onclick method that shows all the buttons registering and firing correctly except the new_game button. Any input on why this might be happening would be appreciated.
Code from OnCreate:
Button acknowledgements = (Button) findViewById(R.id.acknolwedgments_word_Game);
acknowledgements.setOnClickListener(this);
Button quit = (Button) findViewById(R.id.quit_word_game_button);
quit.setOnClickListener(this);
Button new_game = (Button) findViewById(R.id.word_game_new_Button);
Log.e("NEW GAME BUTTON", String.valueOf(new_game));
new_game.setOnClickListener(this);
Log.e("SET ONCLICK", "DONE");
OnClickListener:
public void onClick(View view) {
int id = view.getId();
Log.e("CLICKED BUTTON", String.valueOf(view));
if (id == R.id.quit_word_game_button){
Intent i = new Intent(this, Game.class);
startActivity(i);
}
else if (id == R.id.acknolwedgments_word_Game){
Intent i = new Intent(this, Acknowledgements.class);
startActivity(i);
}
else if (id == R.id.word_game_new_Button){
final AlertDialog alert = new AlertDialog.Builder(word_game_mainscreen.this).create();
final EditText edit = new EditText(getBaseContext());
edit.setHint("Username");
alert.setView(edit);
alert.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
alert.dismiss();
}
});
alert.setButton(DialogInterface.BUTTON_POSITIVE, "PLAY!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String opponent = String.valueOf(edit.getText());
new AsyncTask(){
#Override
protected Object doInBackground(Object[] objects) {
//Code to synchronize it to a server
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
Log.e("POST EXECUTE", (String)o);
//Creates intent to take you to the game
}
}.execute();
}
});
alert.show();
}
else if (id == R.id.togglesound){
ToggleButton music = (ToggleButton) findViewById(R.id.togglesound);
if (music.isChecked()){
Music.play(this, R.raw.wordgame);
}
else{
Music.stop(this);
}
}
}
Simple suggestion: swith case is far better than if-else and class_name.this is mostly friendly than getBaseContext().
For showing AlertDialog we have to first create the builder.Something like:
AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(...).setTitle(...)
.setView(...)
.setPositiviButton(...)
.setNegativeButton(...);
//Now create the builder and assign to AlertDialog
dialog = builder.create();
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