How to close a custom dialog automatically - java

I want to open a dialog. And dismiss automatically after a few seconds, the button in the dialog should also dismiss a dialog, whatever happens first. But I can't find the right way to close the dialog after time is up
I use the next custom dialog
private void okShowDialog(String title, String message){
vibrate();
final Dialog dialogo=new Dialog(Login.this);
dialogo.setContentView(R.layout.okdialog);
dialogo.setCancelable(false);
TextView errorTitle=dialogo.findViewById(R.id.lblTitleDialog);
errorTitle.setText(title);
TextView errorMessage=dialogo.findViewById(R.id.txtErrorDialog);
errorMessage.setText(message);
Button dialogButton = (Button) dialogo.findViewById(R.id.btnCont);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
dialogo.show();
}
The dialog XML is very simple, it just shows a title, message, and button.
I've been through this for a couple of days and can't figure out how to solve it.

You can try to add Handler:
dialogo.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
// Close dialog after 1000ms
dialogo.cancel();
}
}, 1000);
After 1000 ms (1 sec) Your dialog will be closed. I think that You don't have to check if a dialog was closed with a button and when You call again close on closed dialog You won't get any error but if I am not right just add a boolean variable to control if a dialog was closed by a button.

You could also use Kotlin Coroutine:
'build your dialog...'
dialog.setOnShowListener {
CoroutineScope(Dispatchers.Main).launch {
delay(length)
dialog.dismiss()
}
}
dialog.show()
Where 'length' is the time in milliseconds that you want the dialog to show for.

Related

How to dismiss dialog box before further processing?

I have an alertDialog that takes input for further processing. Because the processing can take a while, I want to close the alertDialog and display an image during the time it is doing the process method. The problem is that process() is called before the dialog is actually dismissed. So during that loading time the program basically 'hangs', displaying the alert dialog until process() finishes, after which the image is shown for a split second, defeating its purpose.
I have tried showing the image in the process() method, and tried doing dialog.dismiss() in a synchronized method, but the result stays the same.
alertDialogBuilder.setCancelable(true).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
final String input = et.getText().toString();
dialog.dismiss(); //finish this first
process(input); //then do this
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
You may use
alertDialogBuilder.setOnDismissListener(new
DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//do work on dismiss of dialog
}
});
So,you can show the image in this section and start your process as well. Add a callback listener to process end and use the callback to make the image invisible when the process ends.
It should be as simple as
final String input = et.getText().toString();
dialog.dismiss();
// run in background
AsyncTask.execute(new Runnable() {
#Override
public void run() {
process(input);
}
});

Closing a dialog window when a user selects an item from the list in android

I found a custom BlurDialog on github for android. It opens up a new dialog window with options and blurs the background of the rest of the screen. I have it working perfectly, but I am running into an issue where if I select an item in the options list, it will launch the correct activity, but then when I hit the back button I get back to the previous activity and the dialog window is still open. The only way to close it is by clicking outside the dialog window.
I am trying to find out how to close the dialog window before launching the new activity, so that when the user goes back to that screen the dialog window isn't open anymore. I am still new to android, so I am sure I am missing something extremely simple, I just can't figure it out. Here is the "onCreateDialog" method in my fragment that creates the blurred dialog window...
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_profile_dialog, null);
TextView text = (TextView) view.findViewById(R.id.follow_or_unfollow);
if(isSelf) {
text.setText("Edit Profile");
} else {
text.setText((isFollowing) ? "UnFollow" : "Follow");
}
RelativeLayout followButton = (RelativeLayout) view.findViewById(R.id.follow_layout);
RelativeLayout chatButton = (RelativeLayout) view.findViewById(R.id.chat_layout);
followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//NEED TO CLOSE DIALOG WINDOW HERE
if(isSelf) {
//activate ProfileEditActivity
getActivity().startActivity(new Intent(getActivity(), EditProfileActivity.class));
} else {
Map<String, Object> updates = new HashMap<>();
if(isFollowing) {
//unfollow
updates.put("/following/" + user.getUid() + "/users/" + userID, null);
updates.put("/followers/" + userID + "/users/" + user.getUid(), null);
} else {
updates.put("/following/" + user.getUid() + "/users/" + userID, true);
updates.put("/followers/" + userID + "/users/" + user.getUid(), true);
//follow
}
database.getReference().updateChildren(updates);
getFragmentManager().beginTransaction().remove(ProfileDialogFragment.this).commit();
}
}
});
chatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(), "Implement the start activity for chat", Toast.LENGTH_SHORT).show();
}
});
builder.setView(view);
return builder.create();
}
I have tried looking through the sample apps on the github page here Blurred Dialog Github
But it only shows how to activate the dialog, not how to actually close it when a user selects an item in the dialog. Everything else is working perfectly, if I click an item it launches the correct activity, and if I click outside the dialog the dialog closes. I just need to close it programmatically after a user clicks an item in the dialog. Thank you.
Instead of final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()) create dialog using final AlertDialog builder = new AlertDialog.Builder(getActivity()).create() and show the dilaog after stting view like dialog.show().
Whenver user clicks something on the screen you can close the dialog using the dialog object like dialog.dismiss() i.e inside your follow button click
followButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss()
//YOUR CODE SHOULD COME HERE
}
});
According to the developer site https://developer.android.com/reference/android/app/DialogFragment.html
"Note that in this case the fragment is not placed on the back stack, it is just added as an indefinitely running fragment. Because dialogs normally are modal, this will still operate as a back stack, since the dialog will capture user input until it is dismissed. When it is dismissed, DialogFragment will take care of removing itself from its fragment manager."
Maybe if you call dismiss() it will work.
Public methods
void dismiss()
Dismiss the fragment and its dialog.

Android ProgressDialog not showing (blocked by code in other Thread)

Looking to similar questions everybody solve the problem of not appearing their Progress Dialog putting the intermediate code in a separate Thread.
My problem is that the mentioned solution is not working for me.
In my activity:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.dialog_ddbb_download_text)
.setPositiveButton(R.string.Accept, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// In this method I show the progress dialog
showProgressAndDownloadDDBB();
}
})
.setNegativeButton(R.string.Cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
builder.create().show();
Method in the activity:
private void showProgressAndDownloadDDBB() {
progressDialog = new ProgressDialog(mContext);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
// Here I call the Runnable to execute the code in other Thread and let the UI draw the Progress Dialog. If it wasn't called, the progress dialog does appear.
DDBB_Download_Manager ddbb_download_manager = new DDBB_Download_Manager(mContext, progressDialog);
ddbb_download_manager.run();
}
My runnable class, expected to run the intermediate code in a separate Thread:
public class DDBB_Download_Manager implements Runnable {
public DDBB_Download_Manager(Context context, ProgressDialog progressDialog) {
this.mContext = context;
this.mProgresDialog = progressDialog;
}
#Override
public void run() {
someCode()
Thread.sleep(3000);
// The GUI shows the accept Button clicked for 3 seconds (like it was freezed)
// Here I try to hide the Progress dialog after finishing the job, but it doesn't matter becasuse the progress dialog didn't even show up.
View rootView = ((Activity)mContext).getWindow().getDecorView().findViewById(android.R.id.content);
rootView.post(new Runnable() {
#Override
public void run() {
mProgresDialog.dismiss();
}
});
}
So the question is:
if I am executing the code between the Show and Dismiss methods of the Progress Dialog in a different Thread than the UI Thread, why is not the dialog showing up?
In fact it appears If I don't call the Runnable.
That is because you are running directly the dismiss() method from the runnable when you call ddbb_download_manager.run() where the progress dialog is cleared/done and if you are not calling it then the progress dialog will show due to that dismiss is on yet been called.
Make sure that you call ddbb_download_manager.run() when you want your progress dialog to be dismissed. don't call it directly after you show your progress dialog.
private void showProgressAndDownloadDDBB() {
progressDialog = new ProgressDialog(mContext);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
// Here I call the Runnable to execute the code in other Thread and let the UI draw the Progress Dialog. If it wasn't called, the progress dialog does appear.
DDBB_Download_Manager ddbb_download_manager = new DDBB_Download_Manager(mContext, progressDialog);
Handler handler = new Handler();
handler.postDelayed(ddbb_download_manager ,3*1000);
}

Using a common dialog box, but calling different functions from diffrent activities in android

In my app i have to use same dialog box on all the activities but then on to the click of button on dialog box i need to perform different operations for different activities, i have kept a common code for dialog but then how to call different functions, here is my code:
final Dialog dialog = new Dialog(mContext,R.style.Theme_Levels);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert);
TextView title = (TextView)dialog.findViewById(R.id.title);
title.setText("Network Error");
TextView msg = (TextView)dialog.findViewById(R.id.msg_txt);
msg.setText("The system is down, please check after some time ");
ImageView cancel = (ImageView)dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView continue_btn = (TextView)dialog.findViewById(R.id.continue_btn);
continue_btn.setBackgroundResource(R.drawable.feedback_button_purple);
continue_btn.setText("Retry");
continue_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//TODO perform different operation depending upon from where this function has been called
dialog.dismiss();
}
});
dialog.show();
Create an interface, say DialogActivity, with one method "handlePositiveButton". Let all your Activities implement this interface. From the Dialog.onClick you do this:
DialogActivity activity = (DialogActivity) getActivity();
activity.handlePositiveButton();
Put the code you have specified in a function of a Utils file.
Then pass the positive button onclick listener in that function.
Refer the below code.
public static void showAlertDialog(OnClickListener listener) {
// enter your code here
continue_btn.setOnClickListener(listener);
// more code here
}

How to update AlertDialog content using showDialog(id)

i want to have in my application an alertdialog, that has its message updated everytime it is showed.
This is because the dialog box value depends on some values on the application.
Now i tried to use the showDialog method:
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
showDialog(RESULT_DIALOG);
return false;
}
But once the dialog is created, it doesn't change the message (i know that if the dialog is created, it use the started version).
My onCreateDialog method code is:
public Dialog onCreateDialog(int dialogId) {
AlertDialog dialog;
switch(dialogId) {
case RESULT_DIALOG:
// do the work to define the pause Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(localTv.getText())
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
There is a way to update the content of the AlertDialog.
Actually i create a new dialog box every time the onTouch event is called. But i'm not sure that it is the cleanest way to solve that problem.
Any idea?
Thanks :)
You have to use onPrepareDialog method:
#Override
protected void onPrepareDialog ( int id, Dialog dialog ) {
switch ( id ) {
case RESULT_DIALOG:
AlertDialog alertDialog = ( AlertDialog ) dialog;
alertDialog.setMessage( localTv.getText() );
break;
}
super.onPrepareDialog( id, dialog );
}
From http://developer.android.com/guide/topics/ui/dialogs.html :
Before the dialog is displayed, Android also calls the optional
callback method onPrepareDialog(int, Dialog). Define this method if
you want to change any properties of the dialog each time it is
opened. This method is called every time a dialog is opened, whereas
onCreateDialog(int) is only called the very first time a dialog is
opened. If you don't define onPrepareDialog(), then the dialog will
remain the same as it was the previous time it was opened. This method
is also passed the dialog's ID, along with the Dialog object you
created in onCreateDialog().
You can always change the dialog using onPrepareDialog or you can remove the dialog (so it will always pass through onCreateDialog) setting the onDismiss (dialog.setOnDismiss) to remove the dialog id (removeDialog(id)).

Categories

Resources