user2150591
user2150591

Reputation: 43

Using Boolean Android

I am trying to check if a level is complete in my game by calling a boolean. I want to press a button in my activity which will then check to see if the level is complete if "true" the level will load and if "false" it will display a toast saying level locked. I can get the boolean to save in my prefs correctly but calling it back is becoming a real pain. Below is my code.

My Method for saving:

SharedPreferences gamesettings =
                this.getSharedPreferences("GameProgress",0);

            SharedPreferences.Editor Edit = gamesettings.edit();
            Edit.putBoolean("level1",true);
            Edit.commit();


My menu where i want to call the boolean and start the levels activity:

public class DebugMain extends Activity {

    private Button button;
    private Button button1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.debugmenu);

        addListenerOnButton();

    }

    public void addListenerOnButton() {


        button = (Button) findViewById(R.id.button1);
        button1 = (Button) findViewById (R.id.button2);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {

                 loadSavedPreferences(); {
                SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
                boolean gamesettings = sharedPreferences.getBoolean("level1", true);

                if (gamesettings) {

                    levelcomplete.setChecked(true);
                    Intent intent = new Intent(DebugMain.this, scene1.class);
                    DebugMain.this.startActivity(intent);
                    finish();

                } else {

                    levelcomplete.setChecked(false);
                    Toast.makeText (getApplicationContext(), "Level Locked", Toast.LENGTH_LONG).show ();

                    }

            }

        });

        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {

                 //is level 2 unlocked going here

            }

        });



    }

}

Upvotes: 0

Views: 520

Answers (1)

Ridcully
Ridcully

Reputation: 23665

You save to these preferences:

this.getSharedPreferences("GameProgress",0)

but you try to read from those

PreferenceManager.getDefaultSharedPreferences(this)

These are different preferences. You'll have to use the same for both operations.

Upvotes: 1

Related Questions