Я пишу класс для общих предпочтений, и вы можете легко его использовать и тестировать
package ir.hfathi.students.helper;
import android.content.Context;
import android.content.SharedPreferences;
import androidx.annotation.Nullable;
/**
* Created by Hamid on 07/05/2017.
*/
public class AppPreferenceTools {
private SharedPreferences mPreference;
private Context mContext;
Methods method;
public static final String STRING_PREF_UNAVAILABLE = "string preference unavailable";
public AppPreferenceTools(Context context, String preferenceName) {
if (method == null) method = new Methods();
this.mContext = context;
this.mPreference = this.mContext.getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
}
public SharedPreferences getPreference() {
return mPreference;
}
public void savePreferences(String name, String value) {
mPreference.edit()
.putString(name, value)
.apply();
}
public void savePreferences(String name, int value) {
mPreference.edit()
.putInt(name, value)
.apply();
}
public void savePreferences(String name, Boolean value) {
mPreference.edit()
.putBoolean(name, value)
.apply();
}
public void savePreferences(String name, int value, String PreferencesName) {
this.mPreference = this.mContext.getSharedPreferences(PreferencesName, Context.MODE_PRIVATE);
mPreference.edit()
.putInt(name, value)
.apply();
}
public String getName(String name, @Nullable String defaultSTR) {
return mPreference.getString(name, defaultSTR);
}
public Boolean getName(String name, Boolean defaultBoolean) {
return mPreference.getBoolean(name, defaultBoolean);
}
public String getName(String name, @Nullable String defaultSTR, String Preferences) {
this.mPreference = this.mContext.getSharedPreferences(Preferences, Context.MODE_PRIVATE);
return mPreference.getString(name, defaultSTR);
}
public int getName(String name, @Nullable int defaultSTR) {
return mPreference.getInt(name, defaultSTR);
}
public int getName(String name, @Nullable int defaultSTR, String Preferences) {
this.mPreference = this.mContext.getSharedPreferences(Preferences, Context.MODE_PRIVATE);
return mPreference.getInt(name, defaultSTR);
}
public void removeAllPrefs() {
mPreference.edit().clear().apply();
}
public void removeItemPrefs(String removeItem) {
try {
mPreference.edit().remove(removeItem).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
public int get_count_Preference() {
return mPreference.getAll().size();
}
}
, и я привожу пример, как их использовать
public AppPreferenceTools getAppPreferenceTools(Context context, String PreferenceName) {
return new AppPreferenceTools(context, PreferenceName);
}
getAppPreferenceTools(this, AppConfig.HELP_DASHBOARD)
.getName(AppConfig.HELP_DASHBOARD+header, "non")
getAppPreferenceTools(this, AppConfig.HELP_DASHBOARD)
.savePreferences(AppConfig.HELP_DASHBOARD+header, "show");