質問にはすでに答えがありますが、他の人が来てコードサンプルを探している場合に備えて、SharedPreferencesと対話するためにこのユーティリティクラスをまとめました。
commit()を呼び出すと、使用可能な場合はapply()メソッドが使用されます。それ以外の場合は、古いデバイスではデフォルトでcommit()に戻ります。
public class PreferencesUtil {
SharedPreferences prefs;
SharedPreferences.Editor prefsEditor;
private Context mAppContext;
private static PreferencesUtil sInstance;
private boolean mUseApply;
//Set to private
private PreferencesUtil(Context context) {
mAppContext = context.getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(mAppContext);
prefsEditor = prefs.edit();
//Indicator whether or not the apply() method is available in the current API Version
mUseApply = Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
public static PreferencesUtil getInstance(Context context) {
if (sInstance == null) {
sInstance = new PreferencesUtil(context);
}
return sInstance;
}
public boolean getBoolean(String key, boolean defValue) {
return prefs.getBoolean(key, defValue);
}
public int getInt(String key, int defValue) {
return prefs.getInt(key, defValue);
}
public String getString(String key, String defValue) {
return prefs.getString(key, defValue);
}
public String getString(String key) {
return prefs.getString(key, "");
}
public void putBoolean(String key, boolean value) {
prefsEditor.putBoolean(key, value);
}
public void putInt(String key, int value) {
prefsEditor.putInt(key, value);
}
public void putString(String key, String value) {
prefsEditor.putString(key, value);
}
/**
* Sincle API Level 9, apply() has been provided for asynchronous operations.
* If not available, fallback to the synchronous commit()
*/
public void commit() {
if (mUseApply)
//Since API Level 9, apply() is provided for asynchronous operations
prefsEditor.apply();
else
//Fallback to syncrhonous if not available
prefsEditor.commit();
}
}