zoukankan      html  css  js  c++  java
  • Android应用开发SharedPreferences存储数据的使用方法

    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());

  • 相关阅读:
    【luogu P1343 地震逃生】 题解
    【luogu P3931 SAC E#1
    【luogu P3275 [SCOI2011]糖果】 题解
    【luogu P2947 [USACO09MAR]向右看齐Look Up】 题解
    【luogu P1456 Monkey King】 题解
    【luogu P3377 左偏树(可并堆)】 模板
    【luogu P1993 小K的农场】 题解
    Sqlmap注入Base64编码的注入点
    kali高速更新源以及主题修改方法
    DiscuzX3.1搬家全过程
  • 原文地址:https://www.cnblogs.com/ecollab/p/6028959.html
Copyright © 2011-2022 走看看