1 /* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.sample; 18 19 import android.app.Activity; 20 import android.content.Context; 21 import android.content.SharedPreferences; 22 import android.content.SharedPreferences.Editor; 23 import android.os.Bundle; 24 25 import java.lang.Override; 26 27 /** 28 * A simple activity for using the SharedPreferences API. 29 */ 30 public class SampleDeviceActivity extends Activity { 31 32 private SharedPreferences mPreferences; 33 34 @Override onCreate(Bundle icicle)35 public void onCreate(Bundle icicle) { 36 super.onCreate(icicle); 37 // Get a reference to this context's shared preference. 38 mPreferences = getPreferences(Context.MODE_PRIVATE); 39 } 40 41 /** 42 * Saves the given key value pair to the shared preferences. 43 * 44 * @param key 45 * @param value 46 */ savePreference(String key, String value)47 public void savePreference(String key, String value) { 48 // Get an editor to modify the preferences. 49 Editor editor = mPreferences.edit(); 50 // Insert the key value pair. 51 editor.putString(key, value); 52 // Commit the changes - important. 53 editor.commit(); 54 } 55 56 /** 57 * Looks up the given key in the shared preferences. 58 * 59 * @param key 60 * @return 61 */ getPreference(String key)62 public String getPreference(String key) { 63 return mPreferences.getString(key, null); 64 } 65 66 /** 67 * Deletes all entries in the shared preferences. 68 */ clearPreferences()69 public void clearPreferences() { 70 // Get an editor to modify the preferences. 71 Editor editor = mPreferences.edit(); 72 // Delete all entries. 73 editor.clear(); 74 // Commit the changes - important. 75 editor.commit(); 76 } 77 78 } 79