标签:
转自:http://blog.csdn.net/jingfeizhu/article/details/10017779
SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。实现SharedPreferences存储的步骤如下:
一、根据Context获取SharedPreferences对象
二、利用edit()方法获取Editor对象。
三、通过Editor对象存储key-value键值对数据。
四、通过commit()方法提交数据。
1 public class MainActivity extends Activity {
2 @Override
3 public void onCreate(Bundle savedInstanceState) {
4 super.onCreate(savedInstanceState);
5 setContentView(R.layout.main);
6
7 //获取SharedPreferences对象
8 Context ctx = MainActivity.this;
9 SharedPreferences sp = ctx.getSharedPreferences("pref", MODE_PRIVATE);
10 //存入数据
11 Editor editor = sp.edit();
12 editor.putString("name", "jeff");
13 editor.putInt("score", 0);
14 editor.putBoolean("playagain", true);
15 editor.commit();
16
17 }
18 }
上面的例子使用起来比较麻烦,这里给出一种简单的封装方案:
1 import java.util.Map.Entry;
2
3
4 import android.content.ContentValues;
5 import android.content.Context;
6 import android.content.SharedPreferences;
7
8
9 public class MyPreference {
10
11 private static final String PREFERENCE_NAME = "my.db";
12
13 private SharedPreferences mPreference;
14
15 public MyPreference(Context ctx) {
16 mPreference = ctx.getApplicationContext().getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
17 }
18
19
20 public boolean putStringAndCommit(String key, String value) {
21 return mPreference.edit().putString(key, value).commit();
22 }
23
24
25 public boolean putIntAndCommit(String key, int value) {
26 return mPreference.edit().putInt(key, value).commit();
27 }
28
29 public boolean putBooleanAndCommit(String key, boolean value) {
30 return mPreference.edit().putBoolean(key, value).commit();
31 }
32
33 public boolean putIntAndCommit(ContentValues values) {
34 SharedPreferences.Editor editor = mPreference.edit();
35 for (Entry<String, Object> value : values.valueSet()) {
36 editor.putString(value.getKey(), value.getValue().toString());
37 }
38 return editor.commit();
39 }
40
41
42 public String getString(String key) {
43 return getString(key, "");
44 }
45
46 public String getString(String key, String defValue) {
47 return mPreference.getString(key, defValue);
48 }
49
50 public int getInt(String key) {
51 return getInt(key, -1);
52 }
53
54
55 public int getInt(String key, int defValue) {
56 return mPreference.getInt(key, defValue);
57 }
58
59 public boolean getBoolean(String key) {
60 return getBoolean(key, false);
61 }
62
63 public boolean getBoolean(String key, boolean defValue) {
64 return mPreference.getBoolean(key, defValue);
65 }
66 }
使用方式如下:
1 public class MainActivity extends Activity {
2 @Override
3 public void onCreate(Bundle savedInstanceState) {
4 super.onCreate(savedInstanceState);
5 setContentView(R.layout.main);
6
7 MyPreference pref = new MyPreference(this);
8 pref.putStringAndCommit("name", "jeff");
9
10 }
11 }
标签:
原文地址:http://www.cnblogs.com/yuzhou133/p/4242307.html