智能管家---5. SharePrefrences 封装

这是学习慕课视频入门Android app 的学习笔记,包括源代码以及项目实现的思路

资源下载:https://download.csdn.net/download/ayangann915/10586026

SharePrefrences是一种轻型的数据存储方式,本质是xml文件存储key-value键值对数据,通常存储简单的配置信息。

SharePrefrences对象本身智能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。

实现步骤:
1.根据Context获取SharePrefrences对象
2.利用edit() 方法获取Editor对象
3.通过Editor对象存储key-value键值对数据
4.通过commit()方法提交数据

public class ShareUtils {

    private static String NAME="config";

    //键值对
    private static void putString(Context context,String key,String value){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        sp.edit().putString(key,value).commit();
    }

    //default:默认值,获取失败取得默认值
    private static String getString(Context context,String key,String defalut){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        return sp.getString(key,defalut);
    }

    private static void putInt(Context context,String key,int value){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        sp.edit().putInt(key,value).commit();
    }

    private static int getInt(Context context,String key,int defalut){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        return sp.getInt(key,defalut);
    }

    private static void putBoolean(Context context,String key,boolean value){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        sp.edit().putBoolean(key,value).commit();
    }

    private static boolean getBoolean(Context context,String key,boolean defalut){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        return sp.getBoolean(key,defalut);
    }

    //删除单个,根据key值
    private static void delete(Context context,String key){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        sp.edit().remove(key).commit();
    }

    //删除全部
    private static void deleteALl(Context context){
        SharedPreferences sp=context.getSharedPreferences(NAME,context.MODE_PRIVATE);
        sp.edit().clear().commit();
    }

}

猜你喜欢

转载自blog.csdn.net/ayangann915/article/details/81456431