我正在通过“Sam's Tech Yourself Android应用程序开发24小时”的工作,在某些时候我的昵称和电子邮件设置已经停止正确保存。它现在根本不保存昵称并将电子邮件保存到两者。我做了什么导致这个,我该如何解决?
我认为这些是代码的相关区域,但如果您需要更多,请询问。 据我所知,这仍然是书中的代码,它曾经起作用。也许在某处错字?
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,
""));
}
}
答案 0 :(得分:1)
您必须将这些值初始化为不同的值:
public static final String GAME_PREFERENCES_NICKNAME = "Nickname"; //String
public static final String GAME_PREFERENCES_EMAIL = "Email"; //String
否则,SharedPreferences无法区分这两个键,并且将始终返回找到的第一个键。