Question

I'm trying to create an endgame activity for my Hangman game for android and i'm having some trouble committing values OTHER than strings.

Here is my main activity:

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;
}

I get the sharedprefs like this:

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

And this is where something goes wrong when committing the changes to the editor:

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));
    }

And after changing activity i refetch the values like this:

        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);
    }
    }

But somehow only the String is being committed correctly. I guess the boolean value reverts to the default value of false.

Could someone help me shed some light on this?

Was it helpful?

Solution

If you only want to move the data from one activity to another I would attach it to the Intent. Writing it to shared memory means accessing the phone storage and that is really slow.

You could it do in this way:

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);

In the EndActivity you would do:

Intent intent = getIntent();
String gameString = intent.getStringExtra(GAME_LOGIC_SCORE_STRING, "default value");
boolean win = intent.getBooleanExtra(GAME_LOGIC_WIN_LOOSE, false);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top