سؤال

I am new and I know I will get beat down for this Question but if I get the answer it will be worth it. I have a game that when the user wins the first round I want the save the score and restart the activity instead of going through all of the code and resetting every value. Now How do I keep the score from resetting when the Activity restarts. I dont have example as of yet.

 public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
// SET UP SPINS
private TextView spins;
private Button spin;

// SET UP CONTROLS
private TextView score;
private ProgressBar progressBar;
private static final int SHOW_BONUSACTIVITY = 1;
    int nextspin = 0;
int alert;
int total = 0;
int totalspins = 14;
public int gamescore = 0;
public int currentgamescore = 0;

   @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.play_layout);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Here is where I check if a new game for the first time or if there was a highscore saved to be used here

if (GameState.INSTANCE.getScore() != 0){
        gamescore = GameState.INSTANCE.getScore();}

IF USER WINS THEN THEY ARE SENT TO A BONUS GAME THEN BACK TO SEE IF THEY HAVE FINISHED THE GAME AND NEEDS TO START A NEW

   @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case (SHOW_BONUSACTIVITY): {
        if (resultCode == Activity.RESULT_OK) {
            int bonus = data.getIntExtra("money", 0);
            gamescore=(gamescore + bonus);
            score.setText(String.valueOf("SCORE: " + gamescore));
            if (bigwin == true){

HERE IS WHERE I SAVE THE GAMESCORE TO BRING IT INTO THE NEW ACTIVITY IF THEY WON THE FIRST LEVEL.

                GameState.INSTANCE.addScore(gamescore);
                Intent intent = new Intent(
                MainActivity.this,
                com.bigdaddyapp.android.blingo.MainActivity.class);
                startActivity(intent);  


            }
            }
        }
    }
    }

the next code is the enum activity

public enum GameState {
INSTANCE;

  private int score;
  private GameState(){
    score = 0;
  }

  public int getScore(){
    return score;
  }
  public void addScore(int score){
    this.score += score;
  }

}
هل كانت مفيدة؟

المحلول

As an alternative to storing the values persistent (using Shared Preferences or a SQLite Database), you can also store the values in memory but in a more global context. This way, you'll keep the state over your re-creation of the Activity, but the application will forget them when it's closed.

This might not be what you need for your particular case, but sometimes it's the better option.


Using a Singleton, you can store the state of your application more globally and retrieve it at any point in your code. An example might be:

public enum GameState{
  INSTANCE;

  private int score;
  private GameState(){
    score = 0;
  }

  public int getScore(){
    return score;
  }
  public void addScore(int score){
    this.score += score;
  }

}

It can be used by simply writing:

GameState.INSTANCE.addScore(20);
GameState.INSTANCE.getScore();

There are multiple ways to implement a singleton. In my example, I used the approach Joshua Bloch documented in his Book "Effective Java - Second Edition". See wikipedia for more information.


Extending android.app.Application is another option, thought not as recommended as using the singleton. From the JavaDoc:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

A tutorial on how to do this might be found here (and the linked answer).

نصائح أخرى

You can use SharedPreferences as a simple persistent storage mechanism to save things like the score, lives etc. When the level gets over, save the score via putInt() and when you want to get the score use getInt().

When you want to end the game, do this:

  SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
  SharedPreferences.Editor editor = settings.edit();
  editor.putInt("gamevariable", gamevariable);

  editor.commit();

Then in your onCreate method, get back your variable and use it as you wish:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
myvariable = settings.getInt("gamevariable", false);

As an alternative, I would use standard serialization, which is a more complicated but yet easy option.

First write your integer to a .ser file that you can read later and save it into your project directory:

OutputStream os = new FileOutputStream("myinteger.ser");
ObjectOutput oo = new ObjectOutputStream(os);
oo.writeObject(myinteger);
oo.close();

Then read back your integer into a variable next time you load your activity:

InputStream is = new FileInputStream("myinteger.ser");
ObjectInput oi = new ObjectInputStream(is);
int myinteger = (int) oi.readObject();
oi.close();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top