SharedPreferences 的工具类
来源:互联网 发布:动态效果软件 编辑:程序博客网 时间:2024/06/05 20:50
我们平常保存一些数据,都会用到SharedPreferences,他是保存在手机里面的,具体路径是data/data/你的包名/shared_prefs/保存的文件名.xml, SharedPreferences的使用也很简单,我自己就写了一个SharedPreferences的工具类,然后就保存在这里,等自己以后需要保存数据直接从这里copy代码,哈哈
工具类如下
- package com.example.shortcut;
- import android.content.Context;
- import android.content.SharedPreferences;
-
-
-
-
-
-
-
- public class SharedPreferencesUtils {
-
-
-
- private static final String FILE_NAME = "share_date";
-
-
-
-
-
-
-
-
- public static void setParam(Context context , String key, Object object){
-
- String type = object.getClass().getSimpleName();
- SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sp.edit();
-
- if("String".equals(type)){
- editor.putString(key, (String)object);
- }
- else if("Integer".equals(type)){
- editor.putInt(key, (Integer)object);
- }
- else if("Boolean".equals(type)){
- editor.putBoolean(key, (Boolean)object);
- }
- else if("Float".equals(type)){
- editor.putFloat(key, (Float)object);
- }
- else if("Long".equals(type)){
- editor.putLong(key, (Long)object);
- }
-
- editor.commit();
- }
-
-
-
-
-
-
-
-
-
- public static Object getParam(Context context , String key, Object defaultObject){
- String type = defaultObject.getClass().getSimpleName();
- SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
-
- if("String".equals(type)){
- return sp.getString(key, (String)defaultObject);
- }
- else if("Integer".equals(type)){
- return sp.getInt(key, (Integer)defaultObject);
- }
- else if("Boolean".equals(type)){
- return sp.getBoolean(key, (Boolean)defaultObject);
- }
- else if("Float".equals(type)){
- return sp.getFloat(key, (Float)defaultObject);
- }
- else if("Long".equals(type)){
- return sp.getLong(key, (Long)defaultObject);
- }
-
- return null;
- }
- }
使用也很简单,保存数据- SharedPreferencesUtils.setParam(this, "String", "xiaanming");
- SharedPreferencesUtils.setParam(this, "int", 10);
- SharedPreferencesUtils.setParam(this, "boolean", true);
- SharedPreferencesUtils.setParam(this, "long", 100L);
- SharedPreferencesUtils.setParam(this, "float", 1.1f);
获取数据- SharedPreferencesUtils.getParam(TimerActivity.this, "String", ""); SharedPreferencesUtils.getParam(TimerActivity.this, "int", 0);
- SharedPreferencesUtils.getParam(TimerActivity.this, "boolean", false);
- SharedPreferencesUtils.getParam(TimerActivity.this, "long", 0L);
- SharedPreferencesUtils.getParam(TimerActivity.this, "float", 0.0f);
是不是挺方便的呢,希望对看过文章的你有一点点的帮助!
0 0