How to prevent back button until confirmation message? - java

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.

Related

How to not close AlertDialog android

Hi my problem is when I select an item my AlertDialog dismiss
alertDialog = new AlertDialog.Builder(getActivity());
alertDialog
.setSingleChoiceItems(ageArr, 1, btnSelectItem)
.setPositiveButton(R.string.dialog_ok, btnPositiveAgeDialog)
.setNegativeButton(R.string.dialog_cancel, null)
.show();
what my dialog click positive looks is.
private DialogInterface.OnClickListener btnSelectItem = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedIndexAge = which;
}
};
I tried setting the listener to null and it does not close but still
I needed it because I wanted to know which item is selected
Just put it
itemView.setOnClickListener(null);
or
You can use the implementation of hasOnClickListeners() for knowing the status of listener taken from android.view.View class for
public boolean hasOnClickListeners() {
ListenerInfo li = mListenerInfo;
return (li == null && li.mOnClickListener == null);
}
Use the following link for further modifications
Set listener instance in fragment on application restore
try this
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dialog.dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});
Something else must be closing your AlertDialog. Below is a program that I believe duplicates the minimum requirements you have posted, and selecting one of the items does not close the dialog.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] values = new String[]{ "one", "two", "three", "four" };
DialogInterface.OnClickListener choiceListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "selected index: " + which, Toast.LENGTH_SHORT).show();
}
};
DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "positive button", Toast.LENGTH_SHORT).show();
}
};
new AlertDialog.Builder(this)
.setSingleChoiceItems(values, 1, choiceListener)
.setPositiveButton("ok", positiveListener)
.setNegativeButton("cancel", null)
.show();
}
}

Hide AlertDialog in specific activity

I have one Quote application. When I open the application's MainActivity, if there is new data updated on the server side, one AlertDialog is shown for going to SettingsActivity. It takes some time for appear so if the app is already on SettingsActivity, it is still showing the AlertDialog to go to SettingsActivity.
I want to prevent the AlertDialog from showing in SettingsActivity but continue showing in other activities. My code for AlertDialog is below. How can I do that?
public class UpdatesDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(UpdatesDialogActivity.this);
builder.setTitle("Download New Status");
builder.setMessage("There Are New Status Arrived. Push Download Button From Settings.");
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(UpdatesDialogActivity.this, SettingsActivity.class);
finish();
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
});
builder.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
finish();
return false;
}
});
builder.show();
}
// ==============================================================================
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
You can go for an 'instanceof' check and see if the current activity is settings or else.
if(activity instanceof SettingsActivity){
//don;t show dialog
}else{
//show dialog
}
Hope this will help.

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 can I tell when my Android alert dialog is cancelled?

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

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