2

我正在努力完成“Sam's Tech Yourself Android Application Development in 24 Hours”,在某些时候我的昵称和电子邮件设置停止正确保存。它现在根本不保存昵称并将电子邮件保存到两者。我做了什么导致这种情况,我该如何解决?

我认为这些是代码的相关领域,但如果您需要更多,请询问。据我所知,这仍然是书中的代码,并且它曾经可以工作。也许某处有错字?

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,
                ""));
    }
}
4

1 回答 1

1

您必须将它们初始化为不同的值:

public static final String GAME_PREFERENCES_NICKNAME = "Nickname"; //String
public static final String GAME_PREFERENCES_EMAIL = "Email"; //String

否则 SharedPreferences 无法区分这两个键,并且总是返回找到的第一个键。

于 2012-11-15T18:01:56.570 回答