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