通过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 stub
this.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);

}

原文地址:https://www.cnblogs.com/mf0819/p/3819898.html