将boolean和int保存到sharedPrefs时遇到问题

时间:2010-12-11 10:54:48

标签: android boolean int save sharedpreferences

我正在尝试为Android的Hangman游戏创建一个终结游戏活动,我在提交除字符串以外的值时遇到了一些麻烦。

这是我的主要活动:

package com.assignment.hangman;
import android.app.Activity;


public class HangmanActivity extends Activity {
    public static final String GAME_PREFERENCES = "Game Preferences";
    public static final String GAME_LOGIC = "Game Logic";
    public static final String GAME_LOGIC_GUESS = "Guessed letter";
    public static final String GAME_LOGIC_SCORE_STRING = "Unknow score";
    public static final boolean GAME_LOGIC_WIN_LOOSE = false;
}

我得到这样的sharedprefs:

mGameSettings = getSharedPreferences("GAME_PREFERENCES", Context.MODE_PRIVATE);

这是将更改提交给编辑器时出现问题的地方:

public void finishGame() {
        //Commit different game variables so they can be used in the end game activity  
        Editor editor = mGameSettings.edit();
        editor.putString(GAME_LOGIC_SCORE_STRING, (tries + " of " + numberOfLives + " used"));
        if (tries != numberOfLives){
            editor.putBoolean("GAME_LOGIC_WIN_LOOSE", true);
        }
        editor.commit();
        // Launch end game Activity
        startActivity(new Intent(HangmanGameActivity.this, HangmanEndActivity.class));
    }

在更改活动后,我会重新获取如下值:

        if (mGameSettings.contains("GAME_LOGIC_WIN_LOOSE")) {
        Log.i(GAME_DEBUG, "Succes");
        boolean winLoose = mGameSettings.getBoolean("GAME_LOGIC_WIN_LOOSE", false);
        if (winLoose) {
            winLooseView.setText(R.string.you_win);
        } else {
            winLooseView.setText(R.string.you_loose);
    }
    }

但不知何故只有String正确提交。我猜布尔值恢复为默认值false。

有人可以帮我解释一下吗?

1 个答案:

答案 0 :(得分:3)

如果您只想将数据从一个活动移动到另一个活动,我会将其附加到Intent。 将其写入共享内存意味着访问手机存储,这非常慢。

你可以这样做:

Intent intent = new Intent(HangmanGameActivity.this, HangmanEndActivity.class);
intent.putExtra(GAME_LOGIC_SCORE_STRING, tries + " of " + numberOfLives + " used"):
intent.putExtra("GAME_LOGIC_WIN_LOOSE", true);  
startActivity(intent);

在EndActivity中你会这样做:

Intent intent = getIntent();
String gameString = intent.getStringExtra(GAME_LOGIC_SCORE_STRING, "default value");
boolean win = intent.getBooleanExtra(GAME_LOGIC_WIN_LOOSE, false);