Android 使用SharedPreferences數據存儲

自己寫了個SP輔助類

雖然寫的有點囉嗦,也是自己的成果。如下:

package com.yqy.yqy_testsputil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
/**
 * SP輔助類
 * @author YQY
 *
 *
 */
@SuppressLint("CommitPrefEdits")
public class SPUtil {
	
	private static SharedPreferences mSP;
	private static String spName = "yqy_testsputil";
	
	/**
	 * put
	 * @param context 環境
	 * @param name 鍵
	 * @param object 值
	 */
	public static void put(Context context,String name,Object object){
		mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mSP.edit();
		if(object instanceof String){
			editor.putString(name,(String) object);
		}else if(object instanceof Integer){
			editor.putInt(name, (Integer) object);
		}else if(object instanceof Long){
			editor.putLong(name, (Long) object);
		}else if(object instanceof Float){
			editor.putFloat(name, (Float) object);
		}else if(object instanceof Boolean){
			editor.putBoolean(name, (Boolean) object);
		}
		editor.commit();
	}
	
	public static void set(Context context, String what, String value) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(spName, 0);
		sharedPreferences.edit().putString(what, value).commit();
	}

	public static String getString(Context context,String name){
		mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
		return mSP.getString(name, "");
	}
	public static int getInt(Context context,String name){
		mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
		return mSP.getInt(name, 0);
	}
	public static Long getLong(Context context,String name){
		mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
		return mSP.getLong(name, 0);
	}
	public static Float getFloat(Context context,String name){
		mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
		return mSP.getFloat(name, 0);
	}
	public static boolean getboolean(Context context,String name){
		mSP = context.getSharedPreferences(spName, Activity.MODE_PRIVATE);
		return mSP.getBoolean(name, false);
	}

}


 

發佈了62 篇原創文章 · 獲贊 5 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章