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

来源:互联网 发布:批量查询淘宝小号 编辑:程序博客网 时间:2024/05/19 02:39

    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;             
}



0 0
原创粉丝点击