Android - SharedPreferences

SharedPreferenceAndroid提供的一种轻量级的数据存储方式,主要以键值对的形式存储一些简单的数据。

比如第一次打开某个应用时需要弹出一个提示框,并且这个提示框上还要一个“以后不再提醒”的选项,这种情况我们就可以考虑使用SharedPreference来记住用户的选择情况,以后用户再次打开应用时就根据之前的选择来判断要不要给出提示。

那么,问题就来了,比如当用户第一次选择了下次不再提醒,那么,相应的数据是以什么方式,存在什么地方? 当用户以后打开应用,又怎么读之前存储的数据?… …

先上代码:

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.     public void onCreate(Bundle savedInstanceState) {  
  3.     ... ...  
  4.     promptUser();  
  5.     }  
  6.     private void promptUser() {  
  7.         //获得SharedPreferences对象  
  8.         mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);  
  9.         //读取数据  
  10.         boolean isPromp = mSharedPreferences.getBoolean(prompkey, false);  
  11.         if(!isPromp){  
  12.             showPrompDialog();  
  13.         }  
  14.     }  
  15.     private void showPrompDialog() {  
  16.         AlertDialog.Builder builder = new AlertDialog.Builder(this);   
  17.         LayoutInflater factory = LayoutInflater.from(this);    
  18.         final View promptUserView = factory.inflate(R.layout.promptuser_layout, null);  
  19.           
  20.         builder.setTitle(R.string.promptuser_title);  
  21.         builder.setMessage(R.string.promptuser_content);  
  22.         builder.setView(promptUserView);   
  23.         builder.setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {    
  24.             public void onClick(DialogInterface dialog, int whichButton) {    
  25.                 CheckBox mCheckBox = (CheckBox)promptUserView.findViewById(R.id.checkBox);  
  26.                 Boolean isChecked = mCheckBox.isChecked();  
  27.                 //获得Editor对象  
  28.                 Editor mEditor =mSharedPreferences.edit().putBoolean(prompkey, isChecked);  
  29.                 //提交修改  
  30.                 mEditor.commit();  
  31.             }    
  32.         });    
  33.         builder.setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {    
  34.             public void onClick(DialogInterface dialog, int whichButton) {  
  35.                   
  36.             }    
  37.         });    
  38.         builder.create().show();   
  39.     }  
  40. }  

在使用SharedPreferences时,我们首先需要获取SharedPreferences对象,SharedPreferences的获取有两种方法:一是通过ActivitygetSharedPreferences方法(本质上来讲,该方法是在Context.Java中定义的):

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * Retrieve and hold the contents of the preferences file 'name', returning 
  3.      * a SharedPreferences through which you can retrieve and modify its 
  4.      * values.  Only one instance of the SharedPreferences object is returned 
  5.      * to any callers for the same name, meaning they will see each other's 
  6.      * edits as soon as they are made. 
  7.      * ... ... 
  8.      */  
  9.     public abstract SharedPreferences getSharedPreferences(String name,  
  10.             int mode);  
第一个参数为文件名,如果和name对应的preference file 不存在,那么(以下是API中的说明):

it will be created when you retrieve an editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).

第二个参数为权限,共有4中选择:MODE_PRIVATE、MODE_WORLD_READABLE、MODE_WORLD_WRITEABLE、MODE_MULTI_PROCESS      (Use 0 or {@link #MODE_PRIVATE} for the default operation)

另一种是通过PreferenceManager类的静态方法getDefaultSharedPreferences ()获取SharedPreferences对象。

那这两种方法有什么区别呢?

使用SharedPreferences存取数据实质上就是对/data/data/<package name>/shared_prefs 路径下的xml文件进行读写操作,这就涉及到这个xml文件的文件名和读写权限,使用这两种方法的区别主要就是文件名和权限设置上的区别。

使用第一种方法,我们可以通过第一个参数指定对应的xml文件的文件名,通过第二个参数指定该xml文件的读写权限。

使用第二种方法时,通过PreferenceManager.Java源码我们可以发现:

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * Gets a SharedPreferences instance that points to the default file that is 
  3.      * used by the preference framework in the given context. 
  4.      *  
  5.      * @param context The context of the preferences whose values are wanted. 
  6.      * @return A SharedPreferences instance that can be used to retrieve and 
  7.      *         listen to values of the preferences. 
  8.      */  
  9.     public static SharedPreferences getDefaultSharedPreferences(Context context) {  
  10.         return context.getSharedPreferences(getDefaultSharedPreferencesName(context),  
  11.                 getDefaultSharedPreferencesMode());  
  12.     }  
  13.   
  14.     private static String getDefaultSharedPreferencesName(Context context) {  
  15.         return context.getPackageName() + "_preferences";  
  16.     }  
  17.   
  18.     private static int getDefaultSharedPreferencesMode() {  
  19.         return Context.MODE_PRIVATE;  
  20.     }  
这种方式其实是调用了Context的getSharedPreferences方法,并且,将preference对应的文件名设置为"包名_preferences",将权限设置为MODE_PRIVATE。

知道两种方式的区别后,我们在使用的时候,就很好选择了。

如果在一个应用中只需要用到一个文件来存储,那我们选择PreferenceManager类的静态方法getDefaultSharedPreferences (),如果需要用多个文件来存储数据,那就选择ActivitygetSharedPreferences方法获取SharedPreferences对象以方便根据文件名进行区分,不过可以从这两个方法的实现逻辑看出来,PreferenceManager类的静态方法getDefaultSharedPreferences ()内部调用了Context的getSharedPreferences方法,并且,文件名和权限都是通过get...方法获取到的,所以使用getDefaultSharedPreferences 方法会更影响效率一些。

在获取到preference对象之后,通过查阅API我们可以看到,获取数据主要靠SharedPreferences

getStringgetIntgetLonggetFloatgetBoolean等方法,我们就看看getString()方法的定义吧

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.     * Retrieve a String value from the preferences. 
  3.     *  
  4.     * @param key The name of the preference to retrieve. 
  5.     * @param defValue Value to return if this preference does not exist. 
  6.     *  
  7.     * @return Returns the preference value if it exists, or defValue.  Throws 
  8.     * ClassCastException if there is a preference with this name that is not 
  9.     * a String. 
  10.     *  
  11.     */  
  12. //返回指定的key对应的value,如果不存在返回defValue  
  13.    String getString(String key, String defValue);  

如果需要写数据,则需要在获取到SharedPreferences对象之后,通过Sharedpreference.edit()方法获取编辑器Editor 对象,利用EditorputStringputIntputLongputFloatputBoolean等方法来完成。从API里我们也可以看出SharedPreferences所支持存储的数据类型是哪些。Editor及putString()方法(其他put方法同)的代码如下:

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * Interface used for modifying values in a {@link SharedPreferences} 
  3.      * object.  All changes you make in an editor are batched, and not copied 
  4.      * back to the original {@link SharedPreferences} until you call {@link #commit} 
  5.      * or {@link #apply} 
  6.      */  
  7.     public interface Editor {  
  8.         /** 
  9.          * Set a String value in the preferences editor, to be written back once 
  10.          * {@link #commit} or {@link #apply} are called. 
  11.          *  
  12.          * @param key The name of the preference to modify. 
  13.          * @param value The new value for the preference.  Supplying {@code null} 
  14.          *    as the value is equivalent to calling {@link #remove(String)} with 
  15.          *    this key. 
  16.          *  
  17.          * @return Returns a reference to the same Editor object, so you can 
  18.          * chain put calls together. 
  19.          */  
  20.         Editor putString(String key, String value);  

最后再调用commit()提交设置,写入xml文件。

在写完数据提交时,commit() 方法和apply()方法也是有区别的(待补充)  ... ...

现在,我们来看一下在这个Demo中生成的文件,我们可以进入到data/data/<package name>/shared_prefs 路径下将对应的xml文件导入到本地打开查看:

也可以在黑框中通过adb命令来查看该xml文件:


另外还涉及到的类是

SharedPreferences. OnSharedPreferenceChangeListener

未完待续 ... ...


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值