13.SharedPreference的使用

来源:互联网 发布:香港中文大学gpa算法 编辑:程序博客网 时间:2024/04/30 15:34
package Util;


import android.content.Context;
import android.content.SharedPreferences;


import Bean.UserInfo;


/**用于存储用户信息,在登陆的时候使用判断是否有用户的信息
 * Created by Administrator on 2016/8/23.
 */
public class SharedPreferenceUtil {
    private static final String USER_INF="user_inf";//存储的文件名


    //保存登录用户
    public   void saveLoginUser(Context context ,UserInfo userInfo){
        SharedPreferences sp=context.getSharedPreferences(USER_INF,context.MODE_PRIVATE);//设置为私有的防止外部程序访问
        SharedPreferences.Editor editor=sp.edit();
        editor.putString(userInfo.USER_ID,userInfo.getUserId());
        editor.putString(userInfo.USER_NAME,userInfo.getUserName());
        editor.putString(userInfo.TOKEN,userInfo.getToken());
        editor.putString(userInfo.TOKEN_SECRET,userInfo.getTokenSecret());
        editor.commit();
    }
    //返还数据
    public UserInfo getLoginUser(Context context){
        SharedPreferences sp=context.getSharedPreferences(USER_INF,context.MODE_PRIVATE);
        String userId=sp.getString(UserInfo.USER_ID,"");
        String userName=sp.getString(UserInfo.USER_NAME,"");
        String token=sp.getString(UserInfo.TOKEN,"");
        String tokenSecret=sp.getString(UserInfo.TOKEN_SECRET,"");
        if(userId.equals("")){
            return null;
        }else{
            return new UserInfo(userId,userName,token,tokenSecret,"1");
        }


    }
}
0 0
原创粉丝点击