sharedPreferences 的使用

sharedPreferences 的使用

首选项的使用,一般用于在本地存储交小的数据。用于保存一些常用配置信息文章最后有一个对首选项的封装,可以自己添加其他存储类型

获取首选项的两种方式:
  • 调用Context对象的 getSharedPreferences()
  • 调用Activity对象的 getPreference()
两种方式的区别:
  • 通过getSharePreferences()方法获得的实例对象可以被整个应用程序公用
  • 通过getPreference()方法获得的实例对象只能在当前Activity中使用
sharedPreferences 有四种操作模式:
  1. Context.MODE_APPEND 该模式首先检查文件是否存在,存在则直接追加内容,如果不存在则先创建;
  2. Context.MODE_PRIVATE 该模式为私有模式,也是默认模式,只能被本身的应用访问,写入的内容会覆盖前面的内容
  3. Context.MODE_WORLD_READABLE 全局可读,可以被其他应用读取;
  4. Context.MODE_WORLD_WRITEABLE 标识当前其他应用可以写入文件;
使用步骤:
  • 获取实例对象
    SharedPreferences sp = getSharedPreferences("fileName",Context.MODE_PRIVATE);

  • 获取编辑器
    Editor editor = sp.editor();

  • 存入相关数据

 String  userName = "nuomi"; 
 String passWord = "nuomi"
 editor.put("name",userName);
 editor.put("passWord",passWord);
 edttor.commit();
  • 取出相关数据使用
    SharedPreferences preferences=getSharedPreferences("user", Context.MODE_PRIVATE);
    String name=preferences.getString("name", "defaultname");
    String age=preferences.getString("passWord", "0")

获取方法的第二个参数为取不到的时候的默认值;

为了使用方便我们可以直接将首选项进行封装,将具体实现都封装起来;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class SPUtils {

    private static SharedPreferences getSharedPreference(Context context) {
        return context.getSharedPreferences("config", Context.MODE_PRIVATE);
    }

    /**
     * 这个静态方法只能存放boolean,String
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void put(Context context, String key, Object value) {
        Editor editor = getSharedPreference(context).edit();

        if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        }

        if (value instanceof String) {
            editor.putString(key, (String) value);
        }
        editor.commit();

    }

    /**
     * 
     * @param context
     * @param key
     * @return 布尔值默认为false
     */
    public static boolean getBoolean(Context context, String key) {
        SharedPreferences sp = getSharedPreference(context);
        return sp.getBoolean(key, false);
    }

    /**
     * 
     * @param context
     * @param key
     * @return 字符串默认为""
     */
    public static String getString(Context context, String key) {
        SharedPreferences sp = getSharedPreference(context);
        return sp.getString(key, "");
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值