【SharedPreferences】实例

一、SharedPreferences介绍

    Interface for accessing and modifying preference data returned by Context.getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage. (摘自Android API)
    SharedPreferences是轻量级存储类,存储信息以XML文件的形式保存在/data/data/PACKAGE_NAME /shared_prefs  目录下

二、SharedPreferences用法

   1、存储数据

        
        SharedPreferences pref = Context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
        //PREFERENCES_NAME 存储名称Context.MODE_APPEND 存储模式
        /*
        存储模式有4种,分别为:
        ①MODE_PRIVATE:the default mode, where the created file can only be accessed by the calling application 
                       (or all applications sharing the same user ID).
        ②MODE_APPEND:if the file already exists then write data to the end of the existing file instead of erasing it
        ③MODE_WORLD_READABLE:allow all other applications to have read access to the created file. 
        ④MODE_WORLD_WRITEABLE:allow all other applications to have write access to the created file. 
        后两种存在安全漏洞,不推荐使用
        */
        Editor editor = pref.edit();
        editor.putString("key_string", value_string);
	editor.commit();

  2、取出数据

        
        SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
	String value = pref.getString("key_string", "default_value");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值