David Elliott
David Elliott

Reputation: 113

Storing an int value in android

I'm making an app that gives players a high score. However, the int for the high score resets when I reset the app. Is there a way to save the int so the high score is saved even when the app is restarted?

(I used this code to restart the app):

Intent i = getBaseContext().getPackageManager()
             .getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);

Thanks in advance!

Upvotes: 0

Views: 97

Answers (1)

IntegralOfTan
IntegralOfTan

Reputation: 640

Use this code:

public class SharedPrefs {
    public class SharedKeys {
        final static String highscore = "highscore";
    } 
    public void storeInt(Context context, String key, int data) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(key, data);
        editor.commit();
    }

    public int getInt(Context context, String key) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefs.getInt(key, 0);
    }
}

To store the highscore:

SharedPrefs prefs = new SharedPrefs();
prefs.storeInt(getApplicationContext(), SharedPrefs.SharedKeys.highscore, intScore);

And to retrieve it:

prefs.getInt(getApplicationContext(), SharedPrefs.SharedKeys.highscore)

Comment if you have any questions about how this works.

Upvotes: 3

Related Questions