SharePreference 单例封装 用法
程序员文章站
2022-03-15 13:29:24
import android.content.Context;import android.content.SharedPreferences;/** * SharePreference封装 * */public class PrefUtils { public static final String PREF_NAME = "config"; public static boolean getBoolean(Context ctx, String key, ......
import android.content.Context;
import android.content.SharedPreferences;
/**
* SharePreference封装
*
*/
public class PrefUtils {
public static final String PREF_NAME = "config";
public static boolean getBoolean(Context ctx, String key,
boolean defaultValue) {
SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
return sp.getBoolean(key, defaultValue);
}
public static void setBoolean(Context ctx, String key, boolean value) {
SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
sp.edit().putBoolean(key, value).commit();
}
public static String getString(Context ctx, String key, String defaultValue) {
SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
return sp.getString(key, defaultValue);
}
public static void setString(Context ctx, String key, String value) {
SharedPreferences sf = ctx.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
sf.edit().putString(key, value).commit();
}
public static int getInt(Context ctx, String key, int defaultValue) {
SharedPreferences sp = ctx.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
return sp.getInt(key, defaultValue);
}
public static void setInt(Context ctx, String key, int value) {
SharedPreferences sf = ctx.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
sf.edit().putInt(key, value).commit();
}
}
用法:1 set数据
PrefUtils.setString(LoginActivity.this, GlobalContents.CUSTOMER_ID,
"xxmmmm");
2 get数据
String jwt = PrefUtils.getString(context,LOGIN_INFO,"");
本文地址:https://blog.csdn.net/u014388516/article/details/110630034