简体   繁体   中英

Saving Activity State when back button is clicked

I am creating a basic counter with stats, I am trying to save my activity state when the back button is clicked so the user can check there stats from the main menu. I am able to save the state by using

@Override
public void onBackPressed() {
}

I essentially stored a sharedpreference that gets the number from the counter display. I also have a reset button that is supposed to reset the counter. I have tried using the editor.clear(); editor.commit(); editor.clear(); editor.commit(); (which does nothing) and editor.remove("pref"); editor.commit(); editor.remove("pref"); editor.commit(); (which crashes the app when I click reset). Is there any other way to clear the sharedpreferences?

Have you tried editor.apply() in place of commit(). apply() is available from API level 9 and it commits the changes immediately to in memory sharedpreferences. So, may be you can try this.

There are many possible ways to clear your shared preff which are 1. The simple way is to uninstall your application from your device. 2. the other way is to set the value of the preff object with ""

Example:

  mSharedPrefObjWritable= getSharedPreferences("nameofpref", MODE_WORLD_WRITEABLE);
                SharedPreferences.Editor editor= mSharedPrefObjWritable.edit();
                editor.putString("count", "");
                editor.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM