Search code examples
javaandroidsharedpreferencesandroid-sharedpreferences

Saving an int and displaying it in an alertdialouge using sharedpreferences Android


Hi so im trying to make a game and I want the highscore to be save. From what Ive read its best to used sharedpreference. Here is my code:

I declare the ints here

 public int score;
public int highScore;
SharedPreferences data;
public static String filename = "HighScore";

Then Ive called it in the on create.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    data = getSharedPreferences(filename, 0);

    SharedPreferences.Editor editor = data.edit();
    editor.putInt("Hscore", highScore);
    editor.commit();

}

and now i want to display the highscore in an alertdialouge

  AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
        myAlert.setTitle("You have lost");
        myAlert.setMessage("Your score was :" + score + "\n" + "Your Highscore is :" + \\read highscore and display here)
                .setPositiveButton("OK", new DialogInterface.OnClickListener(){
                    @Override
                public void onClick(DialogInterface dialog, int which){
                        dialog.dismiss();
                        score=0;
                        TextView myScore = (TextView)findViewById(R.id.scoreTxt);
                        String points = String.valueOf(score);
                        myScore.setText(points);
                    }
                })
                .create();

Thank you for your help

public class MainActivity extends ActionBarActivity {

public int score;
public int highScore = 10;
SharedPreferences data;
public static String filename = "HighScore"; // This is shared preference name


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

    data = getSharedPreferences(filename, 0);

   /*SharedPreferences.Editor editor = data.edit();
    editor.putInt("HighScore", highScore);
    editor.apply(); // Use editor.apply() for saving in background*/

    SharedPreferences data = getSharedPreferences(filename, 0);
    int currentscore;
    currentscore = 10;
    highScore = data.getInt("Hscore", 0); // lets say highscore = 100
    if(highScore>currentscore)
    {
        // This will store the new high score in the sharedpreferences.
        SharedPreferences.Editor editor = data.edit();
        editor.putInt("Hscore", highScore);
        editor.commit(); // Use editor.apply() for saving in background
        // after this highscore will be 100
    }

}

public void generateH(View v){
    Random rand = new Random();
    int number = rand.nextInt(2)+1;
    TextView myText = (TextView)findViewById(R.id.coinResult);

           if (number == 1){
        myText.setText("HEADS");
        TextView myScore = (TextView)findViewById(R.id.scoreTxt);
        score = score+1;
        String points = String.valueOf(score);
        myScore.setText(points);


    }

    else{
        myText.setText("TAILS");



        AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
        myAlert.setTitle("You have lost");
        myAlert.setMessage("Your score was :" + score + "\n" + "Your Highscore is: " +  data.getInt("Hscore", 0) )
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create();
        score = 0;
        TextView myScore = (TextView) findViewById(R.id.scoreTxt);
        String points = String.valueOf(score);
        myScore.setText(points);

        myAlert.show();
    }

}
public void generateT(View v){
    Random rand = new Random();
    int number = rand.nextInt(2)+1;
    TextView myText = (TextView)findViewById(R.id.coinResult);

    if(score > highScore){
        highScore = score;
    }


    if (number == 1){
        myText.setText("HEADS");



        AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
        myAlert.setTitle("You have lost");
        myAlert.setMessage("Your score was :" + score + "\n" + "Your Highscore is :" + data.getInt("Hscore", 0))
                .setPositiveButton("OK", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which){
                        dialog.dismiss();
                    }
                })
                .create();

        score = 0;
        TextView myScore = (TextView)findViewById(R.id.scoreTxt);
        String points = String.valueOf(score);
        myScore.setText(points);
        myAlert.show();

    }

    else{
        myText.setText("TAILS");
        TextView myScore = (TextView)findViewById(R.id.scoreTxt);
        score = score+1;
        String points = String.valueOf(score);
        myScore.setText(points);
    }

}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}


Solution

  • The process is simple. Steps to use Sharedpreferences :

    Step 1 : You need to Create a shared preference variable to save high Score.

    Step 2 : Need to save the current high score to the shared preference variable.

    Step 3 : Retrieve the high score when you needed.

    Try the below code :

    public int score;
    public int highScore;
    SharedPreferences data;
    public static String filename = "HighScore"; // This is shared preference name
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    

    // Initializing the shared preference

    data = getSharedPreferences(filename, 0); 
    

    // This is where you insert/store the Highscore value in the shared preference

    SharedPreferences.Editor editor = data.edit(); 
    editor.putInt("Hscore", highScore);
    editor.commit(); // Use editor.apply() for saving in background
    
    } // on create ends
    

    Getting the value from the Sharedpreferences - Syntax

    SharedPreferences sp = getSharedPreferences(filename, 0);
    int value = data.getInt("KEY VALUE", "DEFAULT VALUE"); // If there is no shared preference defined for the given key value default value is returned.
    

    Displaying the High Score in Alert dialog

    SharedPreferences data = getSharedPreferences(filename, 0);
    
    AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
        myAlert.setTitle("You have lost");
        myAlert.setMessage("Your score was :" + score + "\n" + "Your Highscore is :" + data.getInt("Hscore", 0)) // refer syntax
                .setPositiveButton("OK", new DialogInterface.OnClickListener(){
                    @Override
                public void onClick(DialogInterface dialog, int which){
                        dialog.dismiss();
                        score=0;
                        TextView myScore = (TextView)findViewById(R.id.scoreTxt);
                        String points = String.valueOf(score);
                        myScore.setText(points);
                    }
                })
                .create();
    

    Resources :

    Android Developer Page

    Tutorial 1

    Tutorial 2

    Refer the above links..!! which will be much helpful.

    This will help you ..!! try it...

    Updated Answer

    public void generateH(View v){
        Random rand = new Random();
        int number = rand.nextInt(2)+1;
        TextView myText = (TextView)findViewById(R.id.coinResult);
    
        if (number == 1){
            myText.setText("HEADS");
            TextView myScore = (TextView)findViewById(R.id.scoreTxt);
            score = score+1;
            String points = String.valueOf(score);
            myScore.setText(points);
            if(highScore>points)
            {
                // This will store the new high score in the sharedpreferences.
                SharedPreferences.Editor editor = data.edit();
                editor.putInt("Hscore", highScore);
                editor.commit(); // Use editor.apply() for saving in background
                // after this highscore will be 100
            }else
            {
                SharedPreferences.Editor editor = data.edit();
                editor.putInt("Hscore", points);
                editor.commit();
            }
    
        }
    
        else{
            myText.setText("TAILS");
            score = 0;
            TextView myScore = (TextView) findViewById(R.id.scoreTxt);
            String points = String.valueOf(score);
            myScore.setText(points);
            if(highScore>points)
            {
                // This will store the new high score in the sharedpreferences.
                SharedPreferences.Editor editor = data.edit();
                editor.putInt("Hscore", highScore);
                editor.commit(); // Use editor.apply() for saving in background
                // after this highscore will be 100
            }else
            {
                SharedPreferences.Editor editor = data.edit();
                editor.putInt("Hscore", points);
                editor.commit();
            }
    
            AlertDialog.Builder myAlert = new AlertDialog.Builder(this);
            myAlert.setTitle("You have lost");
            myAlert.setMessage("Your score was :" + score + "\n" + "Your Highscore is: " +  data.getInt("Hscore", 0) )
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .create();
    
            myAlert.show();
        }
    
    }