Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJosé Eduardo Eguiguren
17,555 PointsSave a high score for an Android game even after closing the activity or app
I need to store a value somehow permanently to keep the player's highscore. I've seen people used SharedPreferences:
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
However I do not understand exactly how to store the value there and after doing so, how am i supposed to get it back when I need it?
Thank you in advance.
José Eduardo Eguiguren
17,555 PointsSo it works just like passing data with an intent, with the key name representing the variable?
Now once that I store it I just get it later with the method you put in just calling the value with the key right?
Thanks Ashley.
Ashley Alvarado
36 PointsYup you got it.
No problem.
Ashley Alvarado
36 PointsAshley Alvarado
36 PointsI see you have the input part , the "key" is essentially the name of the variable you are passing into the next screen and score is its value. I used this in mine intent.putExtra("types",types); .
And I used this to recieve my values in the next screen. I sent in an arraylist of strings in my example, and wanted to put the list in a function as I called it a few times. This is that code.
public static Intent aop;
public static ArrayList<String> gettypes() { return (ArrayList<String>) aop.getExtras().get( "types"); }
As you can see we recieve our values with the variable name we assigned before. Hope this helps.