Implementing SharedPreferences4:21 with Ben Deitch
In this video I implement SharedPreferences for the application.
To fix that I'm going to use shared preferences. 0:00 I'm going to start by creating a shared preferences field and an editor field. 0:03 So private shared preferences mshared preferences and 0:09 then private sharedpreferences.editor meditor. 0:13 Now that I have these two fields I'm going 0:21 to initialize them right below setContentView. 0:23 So mSharedPreferences = getSharedPreferences. 0:25 And we'll need a preferences file name. 0:31 And then Context.MODE_PRIVATE. 0:33 Alt+Enter to create this constant, and 0:41 I'll call it my package name plus .preferences. 0:45 So com.teamtreehouse.golfscorecard.preferen- 0:49 ces. 0:56 Looks good. 0:59 Then I'll initialize the editor to our mSharedPreferences.edit. 1:01 Great. 1:09 Now we've got access to all the pieces we need and I can start saving the values. 1:09 I'll do that in the on pause method. 1:15 Make some space at the bottom and use control o to override the on pause method. 1:19 And the on pause method, I will want to save the score for 1:27 each whole end to a different shared preference. 1:31 Here is how I will do it. 1:35 First we need to loop through all the holes. 1:38 So for int I, equals zero, I less than M 1:40 holes.length, I plus plus. 1:44 We'll use the editor, so M editor.put.int. 1:51 Because we're storing an Int in our shared preference. 1:56 And we'll use a key of KEY_STROKECOUNT, which I'll create now. 2:00 Alt+Enter, key_strokecount. 2:10 Looks good. 2:15 And then I'm going to add to this key our index, I. 2:19 This is going to make 18 different keys for 2:29 our shared preferences, and is going to let us store 18 different values. 2:33 Then we need to put the value into that key which will be mHoles, 2:39 the holes at that index.get stroke count. 2:47 Perfect. 2:53 Then after the four loop and we've put all of our strokes into the appropriate key. 2:54 We need to call apply to set those changes. 3:01 Looks good. 3:05 Now that we've saved our value in onPause, 3:06 I'm going to retrieve them in onCreate and set them. 3:10 So for each hole, we're going to set strokes 3:15 equal to our SharedPreferences object.getInt, and we'll pass in our key, 3:21 which is KEY_STROKECOUNT plus the index, 3:27 and then we'll pass in a default value of 0. 3:33 And this will set our strokes for each hole. 3:37 All right. 3:43 Looks good. 3:44 Let's see what happens when we run it. 3:45 Now I'm going to put in some values 3, 2, 1, 1. 3:49 Maybe scroll to the bottom. 3:52 Put some in here. 3:57 Give it 10 for hole 15, that'll be easy to check, and 4:00 then I'll hit the back button to completely destroy the activity. 4:03 Let's go back into golf scorecard, and it looks like it saved our values. 4:09 Even the 10 we put for hole 15. 4:15 Great, it looks like our shared preferences are working. 4:17
You need to sign up for Treehouse in order to download course files.Sign up