android开发——SharedPreference的使用(封装为工具类)

1、继承Application(可以全局获取context)

public class ZhonghuaApplication extends Application {

    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

    }

    public static Context getContext() {
        return context;
    }

}

2、修改AndroidMenifest.xml中application的名字

<application
    android:name=".commom.ZhonghuaApplication">

3、制作SharedPreferences工具类

public class SharedPreferencesUtil {
    /**
     * SharedPrefereces的名字
     */
    private final static String SP_NAME = "zhonghuaSharedPreferences";

    /**
     * 存放数据到SharedPreferences
     *
     * @param key
     * @param value
     */
    public static void sharePut(String key, String value) {
        editor().putString(key, value).commit();
    }

    /**
     * 从SharedPreferences中取出数据
     *
     * @param key
     * @return
     */
    public static String shareGet(String key) {
        return sharedPreferences().getString(key, "");
    }

    /**
     * 获取editor
     *
     * @return 返回一个editor对象
     */
    public static SharedPreferences.Editor editor() {
        SharedPreferences sharedPreferences = ZhonghuaApplication.getContext()
                .getSharedPreferences(SP_NAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        return editor;
    }

    /**
     * 获取SharedPreferences对象
     *
     * @return 返回一个对象
     */
    public static SharedPreferences sharedPreferences() {
        SharedPreferences sharedPreferences = ZhonghuaApplication.getContext().getSharedPreferences(SP_NAME,
                Activity.MODE_PRIVATE);
        return sharedPreferences;
    }

}

猜你喜欢

转载自blog.csdn.net/river66/article/details/86570091