Android SharedPreferences存取操作以及封裝詳解

首先初始化

private SP sp;
sp = new SP( context );

存入數據
第一個參數為上下文,第二個參數為key,第三個參數為要存入的數據Value

sp.PutData( context,"AccessToken",AccessToken );

初始化

private SP sp;
sp = new SP( context );

取出數據
第一個參數為上下文,第二個參數為存入數據時定義的名稱,第三個數據為取出數據的默認類型(這個參數很關鍵,再封裝類轉換類型時尤為重要)

AccessToken = (String) sp.GetData( context,"AccessToken","" );

封裝類

public class SP {
    private static SP spInstant;
    private String defaultModelName;
    public SP(){

    }
    public SP (Context context){
        if (spInstant == null){
            spInstant = new SP(  );
            spInstant.defaultModelName = context.getResources().getString( R.string.DefaultModelName );
        }
    }
    public void PutData(Context context,String key,Object value){
        PutData( context,defaultModelName,key,value );
    }
    private void PutData(Context context,String defaultModelName ,String key,Object value){
        SharedPreferences preferences = context.getSharedPreferences( defaultModelName,Context.MODE_PRIVATE );
        SharedPreferences.Editor editor = preferences.edit();
        if (value instanceof Boolean){
            editor.putBoolean( key,(Boolean) value );
        }else if (value instanceof Integer){
            editor.putInt( key,(Integer)value );
        }else if (value instanceof Float){
            editor.putFloat( key,(Float)value );
        }else if (value instanceof Long){
            editor.putLong( key,(Long)value );
        }else if (value instanceof String){
            editor.putString( key,(String)value );
        }else{
            return;
        }
        editor.apply();
    }
    public Object GetData(Context context,String key,Object defaultValue){
        return GetData( context,defaultModelName,key,defaultValue);
    }
    private Object GetData(Context context,String defaultModelName,String key,Object defaultValue){
        SharedPreferences preferences = context.getSharedPreferences( defaultModelName,Context.MODE_PRIVATE );
        if (defaultValue instanceof Boolean){
            return preferences.getBoolean( key,(Boolean) defaultValue );
        }else if (defaultValue instanceof Integer){
            return preferences.getInt( key,(Integer) defaultValue );
        }else if (defaultValue instanceof Float){
            return preferences.getFloat( key,(Float) defaultValue );
        }else if (defaultValue instanceof Long){
            return preferences.getLong( key,(Long) defaultValue );
        }else if (defaultValue instanceof String){
            return preferences.getString( key,(String) defaultValue );
        }else{
            return null;
        }
    }

}

到此這篇關於Android SharedPreferences存取操作以及封裝詳解的文章就介紹到這瞭,更多相關Android SharedPreferences內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: