Reputation: 91
I searched in google. i can find an answer for clearing the shared preference but i need to clear the shared preferences when app getting closed. is this possible pls help.
code clear shared preference
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("UserName", "Tonny");
editor.putInt("UserAge", 20);
editor.commit();
Upvotes: 2
Views: 8758
Reputation: 512706
It would be possible to clear SharedPreferences
every time, either when the main activity is destroyed or when the app is next run. However, as @CommonsWare points out, doing this would miss the whole point of SharedPreferences
. (And check out @CommonsWare's reputation to see whether or not to believe them.) The purpose of SharedPreferences
is to store values to use the next time the app is run. If you clear them automatically every time...
You can just use a variable to store your data. This variable will naturally be cleared every time the app closes.
Upvotes: 6
Reputation: 345
Better to go with other options instead of Shared Preferences.
Using Application class to store the data is one of the options, through which you can achieve your requirement.
Upvotes: -1