Android: Prompt User to Save Changes When Back Button Is Pressed

Android: Prompt user to save changes when Back button is pressed

You're not quite on the right track; what you should be doing is overriding onKeyDown() and listening for the back key, then overriding the default behavior:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
return true;
}

return super.onKeyDown(keyCode, event);
}

If you're only supporting Android 2.0 and higher, they've added an onBackPressed() you can use instead:

@Override
public void onBackPressed() {
// do something on back.
return;
}

This answer is essentially ripped from this blog post. Read it if you need long presses, compatibility support, support for virtual hard keys, or raw solutions like onPreIme() etc.

Prompt user when Back button is pressed

Ask for user's permission to close the
app.

You can do it in the following way;

/**
* Exit the app if user select yes.
*/
private void doExit() {

AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AppDemoActivity.this);

alertDialog.setPositiveButton("Yes", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});

alertDialog.setNegativeButton("No", null);

alertDialog.setMessage("Do you want to exit?");
alertDialog.setTitle("AppTitle");
alertDialog.show();
}

Which is the good place to ask user,
whether (s)he wants to exit the app
when (s)he clicked the back button?

Since, you want to prompt user when (s)he clicked the back hard button, as suggested by others, you can override the onBackPressed() method and call the above method from there;

@Override
public void onBackPressed() {

doExit();
}

As suggested by @Martyn, you can use the onKeyDown to achieve the same;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

if(keyCode == KeyEvent.KEYCODE_BACK) {
doExit();
}

return super.onKeyDown(keyCode, event);
}

The app should also ask if user is
trying to exit the app from a button
(in app itself), not the Back hard
key.

For this, call the doExit() from your button's onClick;

Button exitButton = (Button)findViewById(R.id.exitButton);
exitButton.setOnClickListener(new android.view.View.OnClickListener() {

@Override
public void onClick(View v) {
doExit();
}
});



Related Info:

  • Implementing effective navigation

save the state when back button is pressed

What you have to do is, instead of using KeyCode Back, you have override the below method in your Activity,

@Override
public void onBackPressed() {

super.onBackPressed();
}

And save the state of your Button using SharedPrefrence, and next time when you enter your Activity get the value from the Sharedpreference and set the enabled state of your button accordingly.

Example,

private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("state", button.isEnabled());
editor.commit(); // I missed to save the data to preference here,.
}

private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Boolean state = sharedPreferences.getBoolean("state", false);
button.setEnabled(state);
}

@Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}

onCreate(Bundle savedInstanceState)
{
//just a rough sketch of where you should load the data
LoadPreferences();
}

Save App Preferences from PreferenceScreen when pressing back button

You will need to use

public class AppPreferences extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{

super.onCreate(savedInstanceState);

//setContentView(R.layout.activity_note_detail);

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
SettingsFragment settingsFragment = new SettingsFragment();
fragmentTransaction.add(android.R.id.content, settingsFragment, "SETTINGS_FRAGMENT");
fragmentTransaction.commit();
}

public static class SettingsFragment extends PreferenceFragment
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.app_preferences);

Preference preference = findPreference("background_color");
preference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {

//do your action here

return false;
}
});
}
}

}

Or from other activity:

PreferenceManager.setDefaultValues(this, R.xml.your_setting_xml, false);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

if (settings.getBoolean("background_color", true)) {
//do your action here

.........

Refer to this question also, (it has similar use case):
Checkbox Preference and Checking if its enabled or disable

Keep the data save in sharedPreference although pressed back button - Android Studio

Assign value to present,details,benefit from sharedpref

   SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();

etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);

etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));

In Activity B make sure you save data in onBackPressed()

@Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}

Android - How To Override the Back button so it doesn't Finish() my Activity?

Remove your key listener or return true when you have KEY_BACK.

You just need the following to catch the back key (Make sure not to call super in onBackPressed()).

Also, if you plan on having a service run in the background, make sure to look at startForeground() and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.

@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}


Related Topics



Leave a reply



Submit