Shared Preferences reset data when app is force closed or device is restarted

I have a login screen and wanted the app to appear as if it’s remained “logged in” at the internal screen after the app is closed/destroyed/phone call/etc.

I have a Preferences Object to save values following Login or Register. I read preference values in all the key screen onResume() methods.

After login (for example):

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("sessionId", application.currentSessionId);
editor.putString("userId", application.currentUserId);
editor.putString("userEmail", application.currentUserEmail);
editor.putString("siteUserId", application.currentSiteUserId);
editor.commit();

Within onResume() of Activities:
(ie, within internal screens)

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(activity);
application.currentSessionId = app_preferences.getString("sessionId", "");
application.currentUserId = app_preferences.getString("userId", "");
application.currentUserEmail = app_preferences.getString("userEmail", "");
application.currentSiteUserId = app_preferences.getString("siteUserId", "");

Note. I have application “global” variables, ie, application.currentSessionId, you can just substitute your variables

Try something similar maybe your not saving or retrieving the values correctly because SharePreferences should work

Leave a Comment