首页 > 代码库 > 通过SharePreference来存储登陆状态和账号信息
通过SharePreference来存储登陆状态和账号信息
2014-07-0212:00:19
package com.example.getshareperference;import java.util.Map;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;//封装SharedPreferences类public class SharePreferenceHelper {private Context context;public SharePreferenceHelper(Context context) {// TODO Auto-generated constructor stubthis.context = context;}public boolean saveSharePreference(String filename, Map<String, Object> map) {boolean flag = false;SharedPreferences preferences = context.getSharedPreferences(filename,Context.MODE_PRIVATE);Editor editor = preferences.edit();for (Map.Entry<String, Object> entry : map.entrySet()) {String key = entry.getKey();Object object = entry.getValue();if (object instanceof Boolean) {boolean b = (boolean) object;editor.putBoolean(key, b);}if (object instanceof String) {String s = (String) object;editor.putString(key, s);}if (object instanceof Integer) {Integer i = (Integer) object;editor.putInt(key, i);}if (object instanceof Float) {Float f = (Float) object;editor.putFloat(key, f);}if (object instanceof Long) {Long l = (Long) object;editor.putLong(key, l);}}editor.commit();return flag;}}
//主函数中
private void setMsg() {
SharePreferenceHelper sharePreferenceHelper=new SharePreferenceHelper(this);
Map<String,Object>map=new HashMap<String,Object>();
map.put("username", "admin");
map.put("password", "123");
map.put("age", 23);
map.put("id", 1823855324);
map.put("isManager", true);
sharePreferenceHelper.saveSharePreference("sharefile", map);
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。