Android 数据存储之SharedPreferences存储小记
前言
Android的數(shù)據(jù)存儲機制中還提供了SharedPreferences,SharedPreferences是這其中最容易理解的數(shù)據(jù)存儲技術(shù),采用鍵值對的方式進(jìn)行存儲,而且支持存儲多中數(shù)據(jù)類型。
獲取SharedPreferences對象
SharedPreferences文件存放在/data/data/<package name>/shared_prefs/中,在Android的中,主要提供了三種方式進(jìn)行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進(jìn)行存儲
獲取了SharedPreferences對象,進(jìn)行存儲操作就簡單了,實例如下:
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>SharedPreferences進(jìn)行讀取
讀取同樣簡單,代碼如下:
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(); }總結(jié)
通過上面的代碼,可以很清楚的了解SharedPreferences的使用方法,也可以看到SharedPreferences比文件存儲要方便很多。
博客名稱:王樂平博客
博客地址:http://blog.lepingde.com
CSDN博客地址:http://blog.csdn.net/lecepin
總結(jié)
以上是生活随笔為你收集整理的Android 数据存储之SharedPreferences存储小记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信小程序-使用ColorUI
- 下一篇: 前端每隔几秒发送一个请求