android開發SharedPreferences存鍵值對

/* * 讀取UserInfo信息 */ public static UserInfo getUserInfo(Context context) { SharedPreferences sharedPreferce = context.getSharedPreferences( "userinfo", Context.MODE_APPEND); UserInfo userinfo = new UserInfo(); userinfo._id = sharedPreferce.getString("_id", ""); userinfo.avater = sharedPreferce.getString("avater", ""); userinfo.gender = sharedPreferce.getString("gender", ""); userinfo.nickName = sharedPreferce.getString("nickName", ""); userinfo.name = sharedPreferce.getString("name", ""); userinfo.birthday = sharedPreferce.getString("birthday", ""); userinfo.mobile = sharedPreferce.getString("mobile", ""); return userinfo; }session

/**
	 * 獲取用戶ID
	 */
	public static String getUserIDFromSharedPreferce(Context context) {
		SharedPreferences sharedPreferce = context.getSharedPreferences(
				"userinfo", Context.MODE_APPEND);
		return sharedPreferce.getString("_id", "");
	}
// 存Userinfo信息
	@SuppressLint("CommitPrefEdits")
	public static void keepUserInfoToSharedPreference(UserInfo userInfo,
			Context context) {
		try {
			SharedPreferences sharedPreferce = context.getSharedPreferences(
					"userinfo", Context.MODE_APPEND);
			Editor editor = sharedPreferce.edit();
			editor.putString("_id", userInfo._id);
			editor.putString("name", userInfo.name);
			editor.putString("gender", userInfo.gender);
			editor.putString("nickName", userInfo.nickName);
			editor.putString("avater", userInfo.avater);
			editor.putString("birthday", userInfo.birthday);
			editor.putString("mobile", userInfo.mobile);
			editor.putString("exp", userInfo.expirationTime);// 保存過時時間
			editor.putString("sessionToken", userInfo.accessToken);// 保存訪問token
			editor.commit();
			editor.apply();
		} catch (Exception e) {
			LogUtil.e(Util.class, "keepUserInfoToSharedPreference()", e);
		}
	}

/**
	 * 保存用戶號碼
	 */
	public static void keepUserInfoMobileToSP(Context context, String mobile){
		try {
			SharedPreferences sharedPreferce = context.getSharedPreferences(
					"userinfo", Context.MODE_APPEND);
			Editor editor = sharedPreferce.edit();
			editor.putString("mobile", mobile);
			editor.commit();
			editor.apply();
		} catch (Exception e) {
			LogUtil.e(Util.class, "keepUserInfoMobileToSP", e);
		}
	}
相關文章
相關標籤/搜索