I’m working my way through “Sam’s Tech Yourself Android Application Development in 24 Hours” and at some point my Nickname and Email settings stopped saving correctly. It now doesn’t save the Nickname at all and saves the Email to both. What have I done to cause this, and how can I fix it?
I think that these are the relevant areas of the code, but if you need more please ask.
As far as I can tell, this is still code from the book, and it used to work. Maybe a typo somewhere?
public class QuizActivity extends Activity {
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_NICKNAME = null; //String
public static final String GAME_PREFERENCES_EMAIL = null; //String
@Override
protected void onPause() {
super.onPause();
EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
EditText emailText = (EditText) findViewById(R.id.EditText_Email);
String strNickname = nicknameText.getText().toString();
String strEmail = emailText.getText().toString();
// TODO: fix password and email saving and displaying improperly
Editor editor = mGameSettings.edit();
editor.putString(GAME_PREFERENCES_NICKNAME, strNickname);
editor.putString(GAME_PREFERENCES_EMAIL, strEmail);
editor.commit();
Toast.makeText(QuizSettingsActivity.this, R.string.settings_saved,
Toast.LENGTH_SHORT).show();
}
public void initNicknameEntry() {
EditText nicknameText = (EditText) findViewById(R.id.EditText_Nickname);
if (mGameSettings.contains(GAME_PREFERENCES_NICKNAME)) {
nicknameText.setText(mGameSettings.getString(
GAME_PREFERENCES_NICKNAME, ""));
}
}
public void initEmailEntry() {
EditText emailText = (EditText) findViewById(R.id.EditText_Email);
if (mGameSettings.contains(GAME_PREFERENCES_EMAIL)) {
emailText.setText(mGameSettings.getString(GAME_PREFERENCES_EMAIL,
""));
}
}
You must initialize these to distinct values:
Otherwise SharedPreferences cannot distinguish between the two keys and will always return the first key found.