码迷,mamicode.com
首页 > 移动开发 > 详细

Android 使用SharedPreferences数据存储

时间:2015-08-21 13:45:55      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:数据存储   android   sharedpreferences   sputil   

自己写了个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);
	}

}


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android 使用SharedPreferences数据存储

标签:数据存储   android   sharedpreferences   sputil   

原文地址:http://blog.csdn.net/u012885461/article/details/47831735

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!