Android的数据存储机制中还提供了SharedPreferences,SharedPreferences是这其中最容易理解的数据存储技术,采用键值对的方式进行存储,而且支持存储多中数据类型。
SharedPreferences文件存放在/data/data/<package name>/shared_prefs/
中,在Android的中,主要提供了三种方式进行SharedPreferences对象的获取。
1.Context中的getSharedPreferences()
方法
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return mBase.getSharedPreferences(name, mode);
}
2.Activity中的getPreferences()
/** * Retrieve a {@link SharedPreferences} object for accessing preferences * that are private to this activity. This simply calls the underlying * {@link #getSharedPreferences(String, int)} method by passing in this activity's * class name as the preferences name. * * @param mode Operating mode. Use {@link #MODE_PRIVATE} for the default * operation, {@link #MODE_WORLD_READABLE} and * {@link #MODE_WORLD_WRITEABLE} to control permissions. * * @return Returns the single SharedPreferences instance that can be used * to retrieve and modify the preference values. */
public SharedPreferences getPreferences(int mode) {
return getSharedPreferences(getLocalClassName(), mode);
}
3.PreferenceManager中的getDefaultSharedPreferences()
/** * Gets a SharedPreferences instance that points to the default file that is * used by the preference framework in the given context. * * @param context The context of the preferences whose values are wanted. * @return A SharedPreferences instance that can be used to retrieve and * listen to values of the preferences. */
public static SharedPreferences getDefaultSharedPreferences(Context context) {
return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
getDefaultSharedPreferencesMode());
}
获取了SharedPreferences对象,进行存储操作就简单了,实例如下:
public void onClick(View v) {
SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
editor.putString("name", "Xiaoming");
editor.putInt("age", 18);
editor.commit();
Toast.makeText(getApplicationContext(), "SP写入成功", Toast.LENGTH_SHORT).show();
}
这是存储后生成的文件:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="married" value="false" />
<string name="name">Xiaoming</string>
<int name="age" value="18" />
</map>
读取同样简单,代码如下:
public void onClick(View v) {
SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
String str = pref.getString("name", "") + "\n"
+ pref.getInt("age", 0);
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
通过上面的代码,可以很清楚的了解SharedPreferences的使用方法,也可以看到SharedPreferences比文件存储要方便很多。
博客名称:王乐平博客
博客地址:http://blog.lepingde.com
CSDN博客地址:http://blog.csdn.net/lecepin