Android 数据存储与访问之——SharedPreferences保存用户偏好参数

32 篇文章 0 订阅

    Android 数据存储与访问之——SharedPreferences保存用户偏好参数



      本节介绍的是使用SharedPreferences(保存用户偏好参数)保存数据,当我们的应用想要保存用户的一些偏好参数,比如是否自动登陆,是否记住账号密码,是否在Wifi下才能联网等相关信息,如果使用数据库的话,显得有点大材小用了!我们把上面这些配置信息称为用户的偏好设置,就是用户偏好的设置,而这些配置信息通常是保存在特定的文件中!

1、SharedPreferences使用示例:

工具类:

public class SharedHelper {

    private Context mContext;

    public SharedHelper() {
    }

    public SharedHelper(Context mContext) {
        this.mContext = mContext;
    }


    //定义一个保存数据的方法
    public void save(String username, String passwd) {
        SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("username", username);
        editor.putString("passwd", passwd);
        editor.commit();
        Toast.makeText(mContext, "信息已写入SharedPreference中", Toast.LENGTH_SHORT).show();
    }

    //定义一个读取SP文件的方法
    public Map<String, String> read() {
        Map<String, String> data = new HashMap<String, String>();
        SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE);
        data.put("username", sp.getString("username", ""));
        data.put("passwd", sp.getString("passwd", ""));
        return data;
    }
}

2.读取其他应用的SharedPreferences

      获得其他app的Context,而这个Context代表访问该app的全局信息的接口,而决定应用的唯一标识是应用的包名,所以我们可以通过应用包名获得对应app的Context另外有一点要注意的是:其他应用的SP文件是否能被读写的前提就是SP文件是否指定了可读或者可写的权限,我们上面创建的是MODE_PRIVATE的就不可以了

 public Map<String, String> read() { 
              Context othercontext ;



try { othercontext = createPackageContext("com.jay.sharedpreferencedemo", Context.CONTEXT_IGNORE_SECURITY); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //根据Context取得对应的SharedPreferences sp = othercontext.getSharedPreferences("mysp",
 Context.MODE_WORLD_READABLE);
                Map<String, String> data = new HashMap<String, String>();
                data.put("username", sp.getString("username", ""));
                data.put("passwd", sp.getString("passwd", ""));
                return data;             
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值