I am using SharedPreferences to manage a sort of a “session” for the user and keeping them logged in until they explicitly press log out which is when I delete everything from the SharedPreferences.
When a user logs in, I do this:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( LoginActivity.this);
prefs.edit()
.putString("first_name", firstName)
.putString("last_name", lastName)
.putString("email", email)
.putString("user_id", user_id)
.commit();
Its been working 90% of the time, but every so often, this stuff does not get written to SharedPreferences, causing the user to never be seen as logged in by the system.
Any idea why that might happen? Is it a security issue on some phones?
A note: I put these values into the SystemPreferences when a remote server responds after actually adding the data to the database, and even though the data is added to the db, the values aren’t being saved on some devices.
This is the code to get the preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( ProblemioActivity.this);
String firstName = prefs.getString( "first_name", null); // First arg is name and second is if not found.
String lastName = prefs.getString( "last_name", null); // First arg is name and second is if not found.
String email = prefs.getString( "email", null); // First arg is name and second is if not found.
String user_id = prefs.getString( "user_id", null ); // First arg is name and second is if not found.
Thanks!!
Its fine to use SharedPreferences for storing temporary data (like session). But instead of using
commityou should useapply, because commit only saves the changes but doesn’t update the already initialized preference object. And when you use apply, it updates the values of preference object and asynchronously saves (commit) the changes too..