首页 > 代码库 > SPutils,存取简单的字串,int,boolean及javabean对象

SPutils,存取简单的字串,int,boolean及javabean对象

可以结合Gson对javabean转化成字符串实现对象的存取,基本代码如下

 

package com.example.luozhenlonghp.project_aidl_demo;

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

/**
 * use for save data of String,int,boolean,list<anybean>
 * Created by luozhenlonghp on 2017/5/13.
 */

public class SPUtils {

    /**
     *
     * @param context
     * @param
fileName
    
* @param key
    
* @param value
    
*/
   
public static void putString(Context context,String fileName,String key,String value) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key,value);
        edit.commit();
    }

    /**
     *
     * @param
context
    
* @param fileName
    
* @param key
    
* @return if get failed return "";
     */
   
public static String getString(Context context,String fileName,String key) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        String result = sp.getString(key, "");
        return result;
    }

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

    public static int getInt(Context context,String fileName,String key) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        int result = sp.getInt(key, 0);
        return result;
    }
    public static void putBoolean(Context context,String fileName,String key,boolean value) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putBoolean(key,value);
        edit.commit();
    }

    public static boolean getBoolean(Context context,String fileName,String key) {
        SharedPreferences sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
        boolean result = sp.getBoolean(key, false);
        return result;
    }


}

 

SPutils,存取简单的字串,int,boolean及javabean对象