Android SharePreferences存储

2019-11-08  本文已影响0人  KenChen_939

android数据持久化的轻量级存储方案,SharePreferences是使用键值对进行存储的,意思就是当你保存一条数据的时候就要给这条数据提供一个对应的键。在读取的时候通过这个键进行读取。
写了一个工具类分享一下:


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

public class ShareUtil {
    private String name;
    private Context context;

    public ShareUtil(String name, Context context) {
        this.name = name;
        this.context = context;
    }

    public static ShareUtil instance(Context context, String name){
        return new ShareUtil(name,context);
    }
    public <V> void setValue(String key,V value){
        SharedPreferences sp = context.getSharedPreferences(name,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (value instanceof String){
            editor.putString(key,(String) value);
        }else if (value instanceof Integer){
            editor.putInt(key,(Integer) value);
        }else if (value instanceof Long){
            editor.putLong(key,(Long)value);
        }else if (value instanceof Boolean){
            editor.putBoolean(key,(Boolean)value);
        }else if (value instanceof Float){
            editor.putFloat(key,(Float)value);
        }
        editor.commit();
    }

    public <V> V getValue(String key,V defaultValue){
        SharedPreferences sp = context.getSharedPreferences(name,Context.MODE_PRIVATE);
        Object value = defaultValue;
        if (defaultValue instanceof String){
            value = sp.getString(key,(String) defaultValue);
        }else if (value instanceof Integer){
            value = sp.getInt(key,(Integer) defaultValue);
        }else if (value instanceof Long){
            value = sp.getLong(key,(Long) defaultValue);
        }else if (value instanceof Boolean){
            value = sp.getBoolean(key,(Boolean) defaultValue);
        }else if (value instanceof Float){
            value = sp.getFloat(key,(Float) defaultValue);
        }
        return (V) value;
    }

    public void clearData(){
        SharedPreferences.Editor editor = context.getSharedPreferences(name,Context.MODE_PRIVATE).edit();
        editor.clear();
        editor.commit();
    }

}

上一篇下一篇

猜你喜欢

热点阅读