How can I tell when my Android alert dialog is cancelled? - java

Here is my alert:
new AlertDialog.Builder(Activity.this)
.setMessage("You have unsaved text. Are you sure you want to leave?")
.setCancelable(true)
.setNegativeButton("Leave", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
finish();
}
})
.setPositiveButton("Stay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();
Notice how I allow the alert to be cancelable: .setCancelable(true)
How can I run some code once the alert is cancelled by the user pressing the back button?

According to the AlertDialog.Builder documentation on Android's website, you can use the setOnCancelListener (DialogInterface.OnCancelListener onCancelListener) method to handle when the dialog is cancelled.
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog)
{
// do what you need when the dialog is cancelled
}
})
So, your code would change to this:
new AlertDialog.Builder(Activity.this)
.setMessage("You have unsaved text. Are you sure you want to leave?")
.setCancelable(true)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog)
{
// do what you need when the dialog is cancelled
}
})
.setNegativeButton("Leave", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
finish();
}
})
.setPositiveButton("Stay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
}).show();

Related

Android how to use dialogfragment effecitively(using multiple dialog)

I want to show many dialogs in one activity.
I can show one dialog now, but when I add more dialog, it confuses me.
Here is my code.
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
//then create a alertDialog class
String [] age = getActivity().getResources().getStringArray(R.array.age);
String [] job = getActivity().getResources().getStringArray(R.array.job);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("당신의 나이는?");
builder.setItems(age, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((SetUpActivity)getActivity()).textView_age.setText(age[which]);
}
});
builder.setTitle("당신의 직업은?");
builder.setItems(job, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((SetUpActivity)getActivity()).textView_job.setText(job[which]);
}
});
return builder.create();
}
When the user click the button,(and appear dialog box)
Here is a code
new FragmentDialogBox().show(getSupportFragmentManager(),"fragmentDialog");
Maybe I change the tag - "fragmentDialog" part?

how to set the gravity in toast and can i change the position of my alert dialog?

i want to set the gravity of toast in the center of the layout but when i add the gravity and run my app my app restarts and then crasehes. i have tried the toast both ways by taking the object and with out object
here is code of my. the error is also attached
#Override
public void onBackPressed() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit")
.setIcon(R.drawable.ic_baseline_warning_24)
.setMessage("Sure? Your Want to Exit.")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setNeutralButton("Other", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(MainActivity.this, "Click yes for exit.", Toast.LENGTH_SHORT)
.setGravity(Gravity.CENTER, 0,0);
toast.show();
}
}).show();
the error is copied from the run tab
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.androiddevelopment, PID: 3210
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Toast.setGravity(int, int, int)' on a null object reference
at com.example.androiddevelopment.MainActivity$3.onClick(MainActivity.java:52)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:177)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
i have tried this too but issue did not solved
#Override
public void onBackPressed() {
new AlertDialog.Builder(MainActivity.this)
.setTitle("Exit")
.setIcon(R.drawable.ic_baseline_warning_24)
.setMessage("Are you sure you want to exit")
.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
}).setNeutralButton("Help", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(MainActivity.this, "This is an \"Android Studio\" learning app", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0,0);
toast.show();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
Use:
public void onClick(DialogInterface dialog, int which) {
Toast toast = Toast.makeText(MainActivityJava.this, "Click yes for exit.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0,0);
toast.show();
}

How to prevent back button until confirmation message?

In Android Studio, I've used a WebView. So if a user clicks the back button, I want to show a confirmation message before app close.
This is my current code which I used, but it is not working every time
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
The above code is working fine.
If you want to navigate the WebView back to the previous page use below one.
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
}else{
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
}
Can you try with it. Hope it works
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
// If web view have back history, then go to the web view back history
webView.goBack();
} else {
// Ask the user to exit the app or stay in here
exitApp();
}
}
public void exitApp() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Please confirm");
builder.setMessage("Do you want to exit the app?");
builder.setCancelable(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
// Create the alert dialog using alert dialog builder
AlertDialog dialog = builder.create();
// Finally, display the dialog when user press back button
dialog.show();
}
You have to call your confirmation message method inside your Activities onBackPressed Method
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
onBackPressed() // This is Your Confirmation Dialog method
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
}else {
new AlertDialog.Builder(this)
.setTitle("Are you sure?")
.setMessage("Do you want to exit?")
.setPositiveButton("Close", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
This worked for me. Hope it works.

creating alertdialog inside a non activity class

i have a class that implements view.onclicklistener. how do i create an alert dialog from this class which is not an activity class.
i kept on getting this error.
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
this is my code
class LoginView implements View.OnClickListener {
public void onClick(final View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
Do it like this
private Handler mHandler = new Handler(Looper.getMainLooper());
#Override
public void run() {
// ...
mHandler.post(new Runnable() {
public void run() {
// Create your AlertDialog Here...
}
});
// ...
}
try this method in your class:
public static void showAlert(Activity activity) {
new AlertDialog.Builder(activity)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}

how to reload main activity after click "OK" on AlertDialog

I have an AlertDialog and I want the Main Activity to reload after I have click "OK". The problem is after I have click OK my activity returned to the home screen.
JAVA Code :
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"This application needs GPS satellite or Wireless Networks localization enabled"
+ "\n" + "Do you want to enable it?")
.setCancelable(true)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
startActivity(getIntent());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
Help would be appreciated.
Change this code
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
startActivity(getIntent());
}
to
new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivityForResult(new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
Call onCreate method again. But pass null as a parameter.
onCreate(null);

Categories