Android應用開發SharedPreferences儲存資料的使用方法

來源:互聯網
上載者:User

標籤:out   .com   img   android中   xml檔案   event   false   repr   sed   

SharedPreferences是Android中最容易理解的資料存放區技術,實際上SharedPreferences處理的就是一個key-value(索引值對)SharedPreferences常用來儲存一些輕量級的資料。

 使用SharedPreferences儲存資料,其背後是用xml檔案存放資料,檔案存放在/data/data/<package name>/shared_prefs目錄下

/** * 對SharePreference的封裝 *  * @author Kevin *  */public class PrefUtils {    public static void putBoolean(String key, boolean value, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        sp.edit().putBoolean(key, value).commit();    }    public static boolean getBoolean(String key, boolean defValue, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        return sp.getBoolean(key, defValue);    }    public static void putString(String key, String value, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        sp.edit().putString(key, value).commit();    }    public static String getString(String key, String defValue, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        return sp.getString(key, defValue);    }    public static void putInt(String key, int value, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        sp.edit().putInt(key, value).commit();    }    public static int getInt(String key, int defValue, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        return sp.getInt(key, defValue);    }    public static void remove(String key, Context ctx) {        SharedPreferences sp = ctx.getSharedPreferences("config",                Context.MODE_PRIVATE);        sp.edit().remove(key).commit();    }}
View Code

 PrefUtils.putBoolean("is_guide_show", true, this);

 

// 判斷是否需要跳到新手引導
boolean isGuideShow = PrefUtils.getBoolean("is_guide_show",
false, getApplicationContext());

Android應用開發SharedPreferences儲存資料的使用方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.