SharedPreferences的快速保存獲取工具類

SharedPreferences工具類SPHepler

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

public class SPHepler {
    private static Context context;
    private static SPHepler util;

    public static SPHepler getInstance(Context mcontext) {
        context=mcontext;
        if (util == null) {
            util = new SPHepler();

        }
        return util;

    }

    private SPHepler() {
        super();
    }

    private String name = context.getPackageName();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getInt(String key) {

        SharedPreferences sp = context.getSharedPreferences(name,
                Context.MODE_PRIVATE);

        return sp.getInt(key, 0);
    }

    public void setInt(String key, int num) {

        SharedPreferences sp = context.getSharedPreferences(name,
                Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putInt(key, num);
        editor.commit();

    }

    public String getString(String key) {

        SharedPreferences sp = context.getSharedPreferences(name,
                Context.MODE_PRIVATE);

        return sp.getString(key, "");
    }

    public void setString(String key, String str) {

        SharedPreferences sp = context.getSharedPreferences(name,
                Context.MODE_PRIVATE);
        Editor editor = sp.edit();
        editor.putString(key, str);

        editor.commit();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章