2.Android篇——利用SharedPreferences封装本地存储工具类

问题:

有的时候我们一个查询的接口需要重复的请求多次,尽管每次返回的结果是一样的,但是还是需要请求多次,这个时候我们就可以再第一次请求的时候把数据存到我们的缓存中,之后的请求就可以直接调用缓存中没有过期的数据,这里我们奉上工具类代码:

package com.zjxf.utils;

import android.content.SharedPreferences;


public class SharedPrefUtils {

	private static SharedPrefUtils instance;
	private SharedPreferences sp;

	private SharedPrefUtils() {
		sp = BDApplication.getInstance().getSharedPreferences(
				BDApplication.getInstance().getPackageName(), 0);
	}

	public static SharedPrefUtils getInstance() {
		if (instance == null) {
			synchronized (SharedPrefUtils.class) {
				if (instance == null) {
					instance = new SharedPrefUtils();
				}
			}
		}
		return instance;
	}

	public void putStr2SP(String key, String value) {
		sp.edit().putString(key, value).commit();
	}

	public String getStrBykey(String key, String defValue) {
		return sp.getString(key, defValue);
	}

	public void putInt2SP(String key, Integer value) {
		sp.edit().putInt(key, value).commit();
	}

	public Integer getIntByKey(String key, Integer defValue) {
		return sp.getInt(key, defValue);
	}

	public void putFloat2SP(String key, Float value) {
		sp.edit().putFloat(key, value).commit();
	}

	public Float getFloatByKey(String key, Float defValue) {
		return sp.getFloat(key, defValue);
	}

	public void putLong2SP(String key, Long value) {
		sp.edit().putLong(key, value).commit();
	}

	public Long getLongByKey(String key, Long defValue) {
		return sp.getLong(key, defValue);
	}
	
	public void putBoolean2SP(String key, boolean value) {
		sp.edit().putBoolean(key, value).commit();
	}
	
	public Boolean getBooleanByKey(String key, boolean defValue) {
		return sp.getBoolean(key, defValue);
	}

	public void remove(String key) {
		try {
			sp.edit().remove(key).commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
package com.zjxf.utils;

import android.app.Application;

public class BDApplication extends Application {

	private static BDApplication instance;
	
	@Override
	public void onCreate() {
		super.onCreate();
		instance = this;
		CrashHandler.getInstance().init(this.getApplicationContext());
	}
	
	public static BDApplication getInstance(){
		return instance;
	}
}

上面这个全局的类需要在AndroidManifest.xml里面设置一下

然后就可以使用了,用法如下:

 SharedPrefUtils.getInstance().putStr2SP(CacheKeys.LOGIN_SESSION_Id, sessionId); //添加值
 String schoolName = SharedPrefUtils.getInstance().getStrBykey(CacheKeys.THIS_SCHOOL_NAME, StringUtil.EMPTY_STRING); //获取值

猜你喜欢

转载自blog.csdn.net/qq_38821574/article/details/113519406