Ryan
Ryan

Reputation: 10049

Android, finish()ing

I am making a simple app to learn Android at the same time, I am very much a newbie.

So far this is what i have:

the app opens into levels.java which has 8 buttons (in an xml file), when button 8 is clicked,I have this code:

public void button_clicked8(View v) {
        startActivity(new Intent(this, GameScreen.class));
}

which launches my gamescreen activity, after playing my simple addition game, I have a button that says "end" which calls a function with a finish() in it, it also sets a variable gameover=true; , this sends me back to levels.java

but if I press the button 8 again, it does send me to Gamescreen but I find that gameover=true; is still set :(

Why is that? How do I start the activity "fresh"?

Thanks!

Upvotes: 0

Views: 152

Answers (6)

tasnim
tasnim

Reputation: 21

u can declare a static boolean variable gameOver in levels.java.

which u can modify from end button click in GameScreen.java. when finish has been called all d variables r destroyed. u can override GameScreen.java's onCreate(),onResume(),onDestroy(),onStart(),onPause(),onStop() to handle ur variable

Upvotes: 0

nickfox
nickfox

Reputation: 2835

Please read about activity lifecycles here and as far as setting your gameover variable another way to store the value is with SharedPreferences. Do it like this:

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("gameover", true);
editor.commit();

and to read your value, do it like this:

Boolean gameOver = sharedPreferences.getBoolean("gameover", true);

By doing this you are permanently setting your value and will not have to worry about activity lifecycle events.

Upvotes: 0

romy_ngo
romy_ngo

Reputation: 1061

How about reseting gameover value in onCreate() method of GameScreen?

Upvotes: 0

teddy
teddy

Reputation: 197

Use flag for intent when you start Activity.

Upvotes: 1

Rasel
Rasel

Reputation: 15477

I guess you don't want to start the gamescreen when gameOver is true

 public void button_clicked8(View v) {
            if(gameOver) return;
            startActivity(new Intent(this, GameScreen.class));
    }

Upvotes: 1

Andrew White
Andrew White

Reputation: 53496

I suggest your read my answer to another mildly similar question. Basically, finish is exactly the same as the user hitting the back button. It's more-or-less up to you as the developer to change the state based on the interaction from the user (ie via the intent).

For example you could do something like the following...

Intent intent = new Intent();
Bundle bun    = new Bundle();

bun.putBoolean("newGame", true);

intent.setClass(this, GameActivity.class);
intent.putExtras(bun);
startActivity(intent); 

Upvotes: 1

Related Questions