0

I am making a small game in Android, but I don't know hot to save the high score by using SharedPreferences. When I Intent the point in GamePlayActivity, I want to replace the older highscore by the newer highscore if it bigger than the older.

Here is my code:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class GameOverActivity extends Activity{

    TextView tvHighScore, tvScore;
    Button btnRetry;
    int score = 0;
    int highScore = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_gameoveractivity);



        tvHighScore = (TextView) findViewById(R.id.tvHighScore);
        tvScore = (TextView) findViewById(R.id.tvScore);
        btnRetry = (Button) findViewById(R.id.btnRetry);

        Intent getIntent = getIntent();
        score = getIntent.getIntExtra("point", 0);
        tvScore.setText(Integer.toString(score));

        SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
        highScore = prefs.getInt("score", 0);

        if(score > highScore){
            highScore = score;
            tvHighScore.setText(Integer.toString(highScore));
        }

        btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GameOverActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("score", highScore);
        editor.commit();
        super.onDestroy();
    }
}

And XML code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/uefa_champion_league_background">



    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GUESS THE \n FOOTBALL PLAYER"
        android:textSize="30dp"
        android:typeface="serif"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:textColor="@color/red"
        android:textStyle="bold"
        android:shadowColor="@color/green2"
        android:shadowDx="5"
        android:shadowDy="5"
        android:shadowRadius="15"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="186dp"
        android:layout_marginTop="50dp"
        android:layout_marginBottom="50dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@color/blue25"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="GAME OVER"
            android:textSize="40dp"
            android:typeface="serif"
            android:textStyle="bold"
            android:gravity="center"
            android:layout_marginTop="5dp"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="20dp">

            <LinearLayout
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginTop="5dp"
                android:layout_marginLeft="10dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="TOP SCORE"
                    android:typeface="serif"
                    android:textSize="15dp"/>

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="40dp"
                    android:text="1"
                    android:textSize="30dp"
                    android:typeface="serif"
                    android:gravity="center"
                    android:textColor="@color/red2"
                    android:textStyle="bold"
                    android:id="@+id/tvHighScore"/>

            </LinearLayout>

            <Button
                android:layout_width="120dp"
                android:layout_height="80dp"
                android:text="RETRY"
                android:textSize="30dp"
                android:gravity="center"
                android:background="@drawable/button_shape2"
                android:id="@+id/btnRetry"/>

            <LinearLayout
                android:layout_width="100dp"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginTop="5dp"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="10dp">

                <TextView
                    android:layout_width="80dp"
                    android:layout_height="wrap_content"
                    android:text="SCORE"
                    android:typeface="serif"
                    android:textSize="15dp"
                    android:gravity="center"/>

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="40dp"
                    android:text="3"
                    android:textSize="30dp"
                    android:typeface="serif"
                    android:gravity="center"
                    android:textColor="@color/red2"
                    android:textStyle="bold"
                    android:id="@+id/tvScore"/>

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>


</LinearLayout>
halfer
  • 19,824
  • 17
  • 99
  • 186
Twitter khuong291
  • 11,328
  • 15
  • 80
  • 116
  • When you compared highScoreCurrent with highScore in your if statement, both were not initialized yet, thus the default values for them are 0. Also what is the difference between int score and int highScore? – Hussein El Feky Sep 24 '15 at 15:26
  • possible duplicate of [Android Shared preferences example](http://stackoverflow.com/questions/23024831/android-shared-preferences-example) – NightSkyCode Sep 24 '15 at 15:37
  • possible duplicate of [Need to save a high score for an Android game](http://stackoverflow.com/questions/8407286/need-to-save-a-high-score-for-an-android-game) – Viktor Yakunin Sep 24 '15 at 15:44

3 Answers3

2

It is better to save your game high score in SharedPreferences once it is changed. Don't save it during onDestroy() because what if the battery of the user's device has died while he was on the Game Over screen...? It might not be saved immediately.

Replace your whole code with this one:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class GameOverActivity extends Activity {

    TextView tvHighScore, tvScore;
    Button btnRetry;
    int score;
    int highScore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_gameoveractivity);

        tvHighScore = (TextView) findViewById(R.id.tvHighScore);
        tvScore = (TextView) findViewById(R.id.tvScore);
        btnRetry = (Button) findViewById(R.id.btnRetry);

        score = getIntent().getIntExtra("point", 0);
        tvScore.setText(Integer.toString(score));

        SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
        highScore = prefs.getInt("score", 0);

        if (highScore > score) {
            tvHighScore.setText(Integer.toString(highScore));
        } else {
            highScore = score;
            tvHighScore.setText(Integer.toString(highScore));
            prefs.edit().putInt("score", highScore).apply();
        }

        btnRetry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GameOverActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
Hussein El Feky
  • 6,627
  • 5
  • 44
  • 57
  • Nice! But I have a button (High Score) in MainActivity, and when I build, why this GameOverActivity come first? – Twitter khuong291 Sep 24 '15 at 16:40
  • I don't understand you very well, but what I understood is that there is a high score button in your MainActivity. Now what? You can load your high score normally in onCreate() of the HighScoreActivity just as how you loaded the high score in GameOverActivity. – Hussein El Feky Sep 24 '15 at 16:44
  • Wait, you mean GameOverActivity is opened when you click on high score button? You can check its onClickListener and see what intent it's opening. – Hussein El Feky Sep 24 '15 at 16:46
  • In my app GameOverActivity (that mean HighScoreActivity). That problem only happen when I build this app on android studio, when it install in genymotion, it doesn't happen again. – Twitter khuong291 Sep 24 '15 at 16:49
  • What problem exactly? Please clarify more. – Hussein El Feky Sep 24 '15 at 16:52
  • That problem is: the first time building the app, it run on the GameOverActivity, not the MainActivity – Twitter khuong291 Sep 24 '15 at 16:54
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/90545/discussion-between-hussein-el-feky-and-khuong291). – Hussein El Feky Sep 24 '15 at 16:55
0

Storing data in Sharedpreferences :

 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,     
  MODE_PRIVATE).edit();
  editor.putString("name", "abcd");
 editor.putInt("score", 12);
 editor.commit();

Fetching data from shared preferences :

 SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,     
 MODE_PRIVATE); 
 String text1= prefs.getString("name", "0");
 int text2= prefs.getInt("score", 0);

You can use the if condition to check for the score and set it where you want

Put like this

    if(highScoreCurrent > highScore){
        highScore = highScoreCurrent; 
        editor.putInt("score", highScore); 
        editor.commit();
        tvHighScore.setText(Integer.toString(highScore));
    }
Ashish Shukla
  • 1,027
  • 16
  • 36
0

Well declare a Static variables like public static int score,HighScore,prevattemptScore;

Check it every time the game ends,Update the Score based on Previous high Score you get from SharedPrefernces.

     SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
        prevHighScore= prefs.getInt("score", 0);
   if(score > prevattemptScore)//checking for everyattempt
   {
     HighScore=score;
    }
     public void onDestroy(){ //while closing the game save highscore based on latest score value 
        if(HighScore > prevHighScore)
        {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("score", HighScore);
        editor.commit();
        }
       }
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37