下面列出了怎么用android.content.SharedPreferences.Editor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 存放object
*
* @param context
* @param fileName
* @param key
* @param object
* @return
*/
public static boolean put(Context context, String fileName, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, ((Integer) object).intValue());
} else if (object instanceof Boolean) {
editor.putBoolean(key, ((Boolean) object).booleanValue());
} else if (object instanceof Float) {
editor.putFloat(key, ((Float) object).floatValue());
} else if (object instanceof Long) {
editor.putLong(key, ((Long) object).longValue());
} else if (object instanceof Set) {
editor.putStringSet(key, (Set<String>) object);
} else {
editor.putStringSet(key, (Set<String>) object);
}
return editor.commit();
}
private static String getUrlAddParamer(String url, Context context) {
SharedPreferences setting = context.getSharedPreferences(TAG, 0);
if (!setting.getBoolean("isInit", false)) {
try {
Editor edit = setting.edit();
edit.putString(VERSION_NAME, context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
edit.putString(MODEL, Build.MODEL);
edit.putString("version", VERSION.RELEASE);
edit.putString("url", url);
edit.putBoolean("isInit", true);
edit.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
StringBuilder builder = new StringBuilder(url);
builder.append("&model=" + setting.getString(MODEL, ""));
builder.append("&os=android" + setting.getString("version", ""));
builder.append("&version=" + setting.getString(VERSION_NAME, ""));
return builder.toString();
}
/**
* Record the precache event. The event is persisted in shared preferences if the native library
* is not loaded. If library is loaded, the event will be recorded as UMA metric, and any prior
* persisted events are recorded to UMA as well.
* @param event the precache event.
*/
public static void record(int event) {
SharedPreferences sharedPreferences = ContextUtils.getAppSharedPreferences();
long persistent_metric = sharedPreferences.getLong(PREF_PERSISTENCE_METRICS, 0);
Editor preferencesEditor = sharedPreferences.edit();
if (LibraryLoader.isInitialized()) {
RecordHistogram.recordEnumeratedHistogram(
EVENTS_HISTOGRAM, Event.getBitPosition(event), Event.EVENT_END);
for (int e : Event.getEventsFromBitMask(persistent_metric)) {
RecordHistogram.recordEnumeratedHistogram(
EVENTS_HISTOGRAM, Event.getBitPosition(e), Event.EVENT_END);
}
preferencesEditor.remove(PREF_PERSISTENCE_METRICS);
} else {
// Save the metric in preferences.
persistent_metric = Event.addEventToBitMask(persistent_metric, event);
preferencesEditor.putLong(PREF_PERSISTENCE_METRICS, persistent_metric);
}
preferencesEditor.apply();
}
/**
* 存放object
*
* @param context
* @param fileName
* @param key
* @param object
* @return
*/
public static boolean put(Context context, String fileName, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
Editor editor = sp.edit();
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, ((Integer) object).intValue());
} else if (object instanceof Boolean) {
editor.putBoolean(key, ((Boolean) object).booleanValue());
} else if (object instanceof Float) {
editor.putFloat(key, ((Float) object).floatValue());
} else if (object instanceof Long) {
editor.putLong(key, ((Long) object).longValue());
} else if (object instanceof Set) {
editor.putStringSet(key, (Set<String>) object);
} else {
editor.putStringSet(key, (Set<String>) object);
}
return editor.commit();
}
public void setEnvironment(Context context, int i) {
if (context != null && (this.c == null || this.c.get() == null)) {
this.c = new WeakReference(context.getSharedPreferences("ServerPrefs", 0));
}
if (i == 0 || i == 1) {
Editor edit;
switch (i) {
case 0:
edit = ((SharedPreferences) this.c.get()).edit();
edit.putInt("ServerType", 0);
edit.putString(KEY_OPEN_ENV, "formal");
edit.putString(KEY_HOST_QZS_QQ, KEY_HOST_QZS_QQ);
edit.putString(KEY_HOST_OPEN_MOBILE, KEY_HOST_OPEN_MOBILE);
edit.commit();
changeServer();
Toast.makeText(context, "已切换到正式环境", 0).show();
return;
case 1:
edit = ((SharedPreferences) this.c.get()).edit();
edit.putInt("ServerType", 1);
edit.putString(KEY_OPEN_ENV, "exp");
edit.putString(KEY_HOST_QZS_QQ, "testmobile.qq.com");
edit.putString(KEY_HOST_OPEN_MOBILE, "test.openmobile.qq.com");
edit.commit();
changeServer();
Toast.makeText(context, "已切换到体验环境", 0).show();
return;
default:
return;
}
}
f.e(a, "切换环境参数错误,正式环境为0,体验环境为1");
}
private void setCurrentUserEmail(@Nullable String email) {
Editor editor = mSharedPrefs.edit();
if (email == null) {
editor.remove(KEY_CURRENT_USER);
} else {
editor.putString(KEY_CURRENT_USER, email);
}
editor.apply();
}
/**
* �����ť
*
* @param view
*/
public void gxlogin(View view) {
// System.out.println("�����ť�ˣ��洢��������");
String qq = etQQ.getText().toString().trim();
String pwd = etPwd.getText().toString().trim();
if (TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "QQ�Ż������벻��Ϊ�գ�����", 0).show();
return;
}
// �û��Ƿ�ѡ����ס����
boolean isChecked = cbRem.isChecked();
if (isChecked) {
// �洢����
// 2. ��ȡ�༭��Editor
Editor edit = mSp.edit();
// 3. �ñ༭���洢����
edit.putString("qq", qq);
edit.putString("mm", pwd);
// 4. ��Ҫ����ס�ύ����
edit.commit();
Toast.makeText(this, "���ݴ洢�ɹ���", 0).show();
} else {
System.out.println("���洢����");
}
}
/**
* 保存 Token 对象到 SharedPreferences。
*
* @param context 应用程序上下文环境
* @param token Token 对象
*/
public static void writeAccessToken(Context context, Oauth2AccessToken token) {
if (null == context || null == token) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
Editor editor = pref.edit();
editor.putString(KEY_UID, token.getUid());
editor.putString(KEY_ACCESS_TOKEN, token.getToken());
editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
editor.commit();
}
public static void setDisplayLimitPreference(Context context, int value) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
editor.putString(context.getText(R.string.pref_display_limit).toString(), Integer.toString(value));
editor.commit();
}
public static void reset(final Context context)
{
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(context).edit();
edit.clear();
edit.apply();
}
private static void save(@NonNull AccountContext accountContext, String key, String value) {
Context context = AppContextHolder.APP_CONTEXT;
SharedPreferences preferences = context.getSharedPreferences(MasterSecretUtil.getPreferencesName(accountContext), 0);
Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(key, value);
if (!preferencesEditor.commit()) {
throw new AssertionError("failed to save identity key/value to shared preferences");
}
}
private static void putString(String key, String value)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(HeroVideoApp.getInstance());
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.apply();
}
/**
* 清空备份的数据
*
* @param context
*/
public static void clear(Context context) {
Editor editor = SharePrefUtils.getSharePrefEdit(context,
Constants.FEED_SHARE_PREF).edit();
if (editor != null) {
editor.remove(Constants.FEED_SHARE_PREF).commit();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
this.screenshotCapturer.interrupt();
Editor preferences = PreferenceManager.getDefaultSharedPreferences(this).edit();
preferences.putBoolean(BUNDLE_SHOW_MY_LOCATION, this.myLocationOverlay.isMyLocationEnabled());
preferences.putBoolean(BUNDLE_CENTER_AT_FIRST_FIX, this.myLocationOverlay.isCenterAtNextFix());
preferences.putBoolean(BUNDLE_SNAP_TO_LOCATION,
this.myLocationOverlay.isSnapToLocationEnabled());
preferences.putBoolean(BUNDLE_SHOW_PINS, this.showPins);
preferences.putBoolean(BUNDLE_SHOW_LABELS, this.showLabels);
preferences.putString(KEY_MAP_GENERATOR, this.mapGeneratorInternal.name());
preferences.commit();
disableShowMyLocation();
}
public static void setDisplayLimitPreference(Context context, int value) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
editor.putString(context.getText(R.string.pref_display_limit).toString(), Integer.toString(value));
editor.apply();
}
private static boolean setLayoutParamsMotorola(Context context, @SuppressWarnings("unused") int spanX, int spanY, int appWidgetId)
{
// for Motorola devices use spanY
boolean isLargeLayout = spanY != 1;
String preferenceKey = "isLargeLayout_"+appWidgetId;
Editor editor = ApplicationPreferences.getEditor(context);
editor.putBoolean(preferenceKey, isLargeLayout);
editor.apply();
return isLargeLayout;
}
public void saveQZoneLogin(String openid, String access_token, String expires_in) {
Editor editor = context.getSharedPreferences("qzone", 0).edit();
editor.putString("openid", openid);
editor.putString("access_token", access_token);
editor.putString("expires_in", expires_in);
editor.commit();
}
/**
* Put data to shared preferences in private mode.
* @param context - The context of activity which is requesting to put data.
* @param key - Used to identify the value.
* @param value - The actual value to be saved.
*/
public static void putString(Context context, String key, String value) {
SharedPreferences mainPref =
context.getSharedPreferences(context.getResources()
.getString(R.string.shared_pref_package),
Context.MODE_PRIVATE
);
Editor editor = mainPref.edit();
editor.putString(key, value);
editor.commit();
}
static void setEventsBlocked(Context context, boolean eventsBlocked)
{
synchronized (PPApplication.eventsRunMutex) {
Editor editor = ApplicationPreferences.getEditor(context);
editor.putBoolean(PREF_EVENTS_BLOCKED, eventsBlocked);
editor.apply();
ApplicationPreferences.prefEventsBlocked = eventsBlocked;
}
}
SpUtils putIntCommit(String key, int value) {
if (mPref != null) {
Editor editor = mPref.edit();
editor.putInt(key, value);
editor.commit();
return this;
} else throw new RuntimeException("First Initialize context");
}
SpUtils putBoolean(String key, boolean value) {
if (mPref != null) {
Editor editor = mPref.edit();
editor.putBoolean(key, value);
editor.apply();
return this;
} else throw new RuntimeException("First Initialize context");
}
/**
* Set a preference string value
* @param key the preference key to set
* @param value the value for this key
*/
public void setPreferenceStringValue(String key, String value) {
if(sharedEditor == null) {
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}else {
sharedEditor.putString(key, value);
}
}
private void saveHistory() {
if (mInstanceState.filename != null) {
int selstart = mEditor.getSelectionStart();
int selend = mEditor.getSelectionEnd();
SharedPreferences sp = getSharedPreferences(SettingsActivity.PREF_HISTORY, MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(mInstanceState.filename, String.format("%d,%d,%d", selstart, selend,
System.currentTimeMillis()));
editor.commit();
}
}
/**
* Clear client credentials.
* @param context - Application context.
*/
public static void clearClientCredentials(Context context) {
SharedPreferences mainPref = context.getSharedPreferences(Constants.PACKAGE_NAME, Context.MODE_PRIVATE);
Editor editor = mainPref.edit();
editor.putString(Constants.CLIENT_ID, null);
editor.putString(Constants.CLIENT_SECRET, null);
editor.apply();
}
public void setLoggedInApiKey(String apiKey, String email) {
this.api_key = apiKey;
Editor ed = this.settings.edit();
ed.putString(EMAIL, email);
ed.putString(API_KEY, apiKey);
ed.apply();
afterLogin();
}
private static void editSubmit(Editor editor) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
editor.apply();
} else {
editor.commit();
}
}
public static void clearNotificationHubStorageData() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
Editor editor = sharedPreferences.edit();
Set<String> keys = sharedPreferences.getAll().keySet();
for (String key : keys) {
if (key.startsWith("__NH_")) {
editor.remove(key);
}
}
editor.commit();
}
public static void setString(Context context, String key, String value) {
SharedPreferences sp = context.getSharedPreferences(
SHARED_PREFERANCE_NAME, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(key, value);
editor.commit();
}
public void init(Context context, String str) {
if (str == null || str.trim().length() <= 0) {
throw new RuntimeException("please fill the value");
}
Context applicationContext = context.getApplicationContext();
a(applicationContext);
Editor edit = applicationContext.getSharedPreferences("VV_Tracker", 0).edit();
edit.putString("vv_uaid", str);
try {
edit.apply();
} catch (Exception e) {
edit.commit();
e.printStackTrace();
}
}
/** save session time */
public void setAppStartDate() {
SharedPreferences preferences2sessiontime = context.getSharedPreferences("mobclick_agent_state_" + packageName, preferenceMode);
Editor editor = preferences2sessiontime.edit();
Date date = new Date();
SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = localSimpleDateFormat.format(date);
editor.putString("app_start_date", dateStr);
editor.commit();
}