In my application, I extend the application class to maintain information relevant to the authenticated user. However, after running through some tests where I disallow background process, open up another application(thus killing mine), and reopen mine, I notice that this state is lost(variables returning to their default value). I realized that the Application class doesn’t have any lifecycle callbacks, besides onCreate, like the Activities do, which I thought the elegant solution would be. So I decided to write this information to a SharedPreference, so that it can be recovered when needed. Is this the correct solution, or is there a more elegant one?
Relevant sample code for reference:
public class ApplicationUser extends Application {
private static final String PREF_KEY_USER = "prefKeyUser";
private static final String PREF_KEY_ID = "prefKeyID";
private static final String PREF_KEY_FIRST_NAME = "prefKeyFirstName";
private static final String PREF_KEY_LAST_NAME = "prefKeyLastName";
private static final String PREF_KEY_EMAIL = "prefKeyEmail";
private User mUser;
private SharedPreferences mSharedPreferences;
@Override
public void onCreate() {
super.onCreate();
mSharedPreferences = getSharedPreferences(PREF_KEY_USER,MODE_PRIVATE);
}
/**
*
* @return the user
*/
public User getUser() {
if (mUser == null) {
int id = mSharedPreferences.getInt(PREF_KEY_ID, -1);
String firstName = mSharedPreferences.getString(PREF_KEY_FIRST_NAME, "");
String lastName = mSharedPreferences.getString(PREF_KEY_LAST_NAME, "");
String email = mSharedPreferences.getString(PREF_KEY_EMAIL, "");
mUser = new User(id, firstName, lastName, email);
}
return mUser;
}
/**
* sets user, writing to shared preferences as well
* @param user
*/
public void setUser(User user) {
mUser = user;
Editor e = mSharedPreferences.edit();
e.putInt(PREF_KEY_ID, user.getID());
e.putString(PREF_KEY_FIRST_NAME, user.getFirstName());
e.putString(PREF_KEY_LAST_NAME, user.getLastName());
e.putString(PREF_KEY_EMAIL, user.getEmail());
e.commit();
}
}
It seems like the way I did it was the correct way, so I am just going to add this as the answer. If this is the incorrect procedure, please correct me.