У меня есть синглтон для SharedPreferences, дело в том, что я использовал только одно SharedPreferences имя файла, но теперь я хотел бы получить что-то вроде: login_preferences или settings_preferences, как правильно их создать и сделать их одноэлементными? Или мне нужно создать класс по одному для каждого типа LoginSharedPreferences, а другой для SettingsSharedPreferences и выполнять там операции?

0
StuartDTO 20 Дек 2019 в 18:10

1 ответ

да, у вас есть два класса Singleton с разными именами и доступом, как вы сказали.

public class LoginAppState {

    private static final String SETTINGS_NAME = "LoginPrfs";

    private static LoginAppState sSharedPrefs;

    private final SharedPreferences mPref;

    private SharedPreferences.Editor mEditor;

    private boolean mBulkUpdate = false;

    /**
     * Enum representing your setting names or key for your setting.
     */
    public enum Key {
        /* Recommended naming convention:
         * ints, floats, doubles, longs:
         * SAMPLE_NUM or SAMPLE_COUNT or SAMPLE_INT, SAMPLE_LONG etc.
         *
         * boolean: IS_SAMPLE, HAS_SAMPLE, CONTAINS_SAMPLE
         *
         * String: SAMPLE_KEY, SAMPLE_STR or just SAMPLE
         */

        TOKEN_STR,
        EMAIL_STR,
        MEMBERID_STR,
        NAME_STR,
    }

    private LoginAppState(Context context) {
        mPref = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);
    }


    public static LoginAppState getInstance(Context context) {
        if (sSharedPrefs == null) {
            sSharedPrefs = new LoginAppState(context.getApplicationContext());
        }
        return sSharedPrefs;
    }

    public static LoginAppState getInstance() {
        if (sSharedPrefs != null) {
            return sSharedPrefs;
        }

        //Option 1:
        throw new IllegalArgumentException("Should use getClient(Context) at least once before using this method.");

        //Option 2:
        // Alternatively, you can create a new instance here
        // with something like this:
        // getClient(MyCustomApplication.getAppContext());
    }

    public void put(Key key, String val) {
        doEdit();
        mEditor.putString(key.name(), val);
        doCommit();
    }

    public void put(Key key, int val) {
        doEdit();
        mEditor.putInt(key.name(), val);
        doCommit();
    }

    public void put(Key key, boolean val) {
        doEdit();
        mEditor.putBoolean(key.name(), val);
        doCommit();
    }

    public void put(Key key, float val) {
        doEdit();
        mEditor.putFloat(key.name(), val);
        doCommit();
    }

    public void put(Key key, Set<String> set) {
        synchronized (this) {
            doEdit();
            mEditor.remove(AppState.Key.WISHLIST.name());
            doCommit();
            doEdit();
            mEditor.putStringSet(key.name(), set);
            doCommit();
        }

    }

    public void putContestSet(Key key, Set<String> set) {
        synchronized (this) {
            doEdit();
            mEditor.remove(Key.CONTESTLIST.name());
            doCommit();
            doEdit();
            mEditor.putStringSet(key.name(), set);
            doCommit();
        }

    }

    /**
     * Convenience method for storing doubles.
     * <p/>
     * There may be instances where the accuracy of a double is desired.
     * SharedPreferences does not handle doubles so they have to
     * cast to and from String.
     *
     * @param key The enum of the preference to store.
     * @param val The new value for the preference.
     */
    public void put(Key key, double val) {
        doEdit();
        mEditor.putString(key.name(), String.valueOf(val));
        doCommit();
    }

    public void put(Key key, long val) {
        doEdit();
        mEditor.putLong(key.name(), val);
        doCommit();
    }

    public String getString(Key key, String defaultValue) {
        return mPref.getString(key.name(), defaultValue);
    }

    public String getString(Key key) {
        return mPref.getString(key.name(), null);
    }

    public int getInt(Key key) {
        return mPref.getInt(key.name(), 0);
    }

    public int getInt(Key key, int defaultValue) {
        return mPref.getInt(key.name(), defaultValue);
    }

    public long getLong(Key key) {
        return mPref.getLong(key.name(), 0);
    }

    public long getLong(Key key, long defaultValue) {
        return mPref.getLong(key.name(), defaultValue);
    }

    public float getFloat(Key key) {
        return mPref.getFloat(key.name(), 0);
    }

    public float getFloat(Key key, float defaultValue) {
        return mPref.getFloat(key.name(), defaultValue);
    }

    /**
     * Convenience method for retrieving doubles.
     * <p/>
     * There may be instances where the accuracy of a double is desired.
     * SharedPreferences does not handle doubles so they have to
     * cast to and from String.
     *
     * @param key The enum of the preference to fetch.
     */
    public double getDouble(Key key) {
        return getDouble(key, 0);
    }

    /**
     * Convenience method for retrieving doubles.
     * <p/>
     * There may be instances where the accuracy of a double is desired.
     * SharedPreferences does not handle doubles so they have to
     * cast to and from String.
     *
     * @param key The enum of the preference to fetch.
     */
    public double getDouble(Key key, double defaultValue) {
        try {
            String string = mPref.getString(key.name(), String.valueOf(defaultValue));
            if (string == null) {
                return defaultValue;
            }
            return Double.valueOf(string);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public boolean getBoolean(Key key, boolean defaultValue) {
        return mPref.getBoolean(key.name(), defaultValue);
    }

    public boolean getBoolean(Key key) {
        return mPref.getBoolean(key.name(), false);
    }

    public Set<String> getSet(Key key) {
        return mPref.getStringSet(key.name(), new HashSet<>());
    }

    /**
     * Remove keys from SharedPreferences.
     *
     * @param keys The enum of the key(s) to be removed.
     */
    public void remove(Key... keys) {
        doEdit();
        for (Key key : keys) {
            mEditor.remove(key.name());
        }
        doCommit();
    }

    /**
     * Remove all keys from SharedPreferences.
     */
    public void clear() {
        doEdit();
        mEditor.clear();
        doCommit();
    }

    public boolean isLoggedIn() {
        return getString(Key.TOKEN_STR) != null;
    }

    public void edit() {
        mBulkUpdate = true;
        mEditor = mPref.edit();
    }

    public void commit() {
        mBulkUpdate = false;
        mEditor.commit();
        mEditor = null;
    }

    private void doEdit() {
        if (!mBulkUpdate && mEditor == null) {
            mEditor = mPref.edit();
        }
    }

    private void doCommit() {
        if (!mBulkUpdate && mEditor != null) {
            mEditor.commit();
            mEditor = null;
        }
    }
}

и ваш SettingsAppState.java выглядит так

public class SettingsAppState {

    private static final String SETTINGS_NAME = "SettingsPrfs";

    private static SettingsAppState sSharedPrefs;

    private final SharedPreferences mPref;

    private SharedPreferences.Editor mEditor;

    private boolean mBulkUpdate = false;

    /**
     * Enum representing your setting names or key for your setting.
     */
    public enum Key {
        /* Recommended naming convention:
         * ints, floats, doubles, longs:
         * SAMPLE_NUM or SAMPLE_COUNT or SAMPLE_INT, SAMPLE_LONG etc.
         *
         * boolean: IS_SAMPLE, HAS_SAMPLE, CONTAINS_SAMPLE
         *
         * String: SAMPLE_KEY, SAMPLE_STR or just SAMPLE
         */

        TOKEN_STR,
        EMAIL_STR,
        MEMBERID_STR,
        NAME_STR,
    }

    private SettingsAppState(Context context) {
        mPref = context.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);
    }


    public static SettingsAppState getInstance(Context context) {
        if (sSharedPrefs == null) {
            sSharedPrefs = new AppState(context.getApplicationContext());
        }
        return sSharedPrefs;
    }

    public static SettingsAppState getInstance() {
        if (sSharedPrefs != null) {
            return sSharedPrefs;
        }

        //Option 1:
        throw new IllegalArgumentException("Should use getClient(Context) at least once before using this method.");

        //Option 2:
        // Alternatively, you can create a new instance here
        // with something like this:
        // getClient(MyCustomApplication.getAppContext());
    }

    public void put(Key key, String val) {
        doEdit();
        mEditor.putString(key.name(), val);
        doCommit();
    }

    public void put(Key key, int val) {
        doEdit();
        mEditor.putInt(key.name(), val);
        doCommit();
    }

    public void put(Key key, boolean val) {
        doEdit();
        mEditor.putBoolean(key.name(), val);
        doCommit();
    }

    public void put(Key key, float val) {
        doEdit();
        mEditor.putFloat(key.name(), val);
        doCommit();
    }

    public void put(Key key, Set<String> set) {
        synchronized (this) {
            doEdit();
            mEditor.remove(AppState.Key.WISHLIST.name());
            doCommit();
            doEdit();
            mEditor.putStringSet(key.name(), set);
            doCommit();
        }

    }

    public void putContestSet(Key key, Set<String> set) {
        synchronized (this) {
            doEdit();
            mEditor.remove(Key.CONTESTLIST.name());
            doCommit();
            doEdit();
            mEditor.putStringSet(key.name(), set);
            doCommit();
        }

    }

    /**
     * Convenience method for storing doubles.
     * <p/>
     * There may be instances where the accuracy of a double is desired.
     * SharedPreferences does not handle doubles so they have to
     * cast to and from String.
     *
     * @param key The enum of the preference to store.
     * @param val The new value for the preference.
     */
    public void put(Key key, double val) {
        doEdit();
        mEditor.putString(key.name(), String.valueOf(val));
        doCommit();
    }

    public void put(Key key, long val) {
        doEdit();
        mEditor.putLong(key.name(), val);
        doCommit();
    }

    public String getString(Key key, String defaultValue) {
        return mPref.getString(key.name(), defaultValue);
    }

    public String getString(Key key) {
        return mPref.getString(key.name(), null);
    }

    public int getInt(Key key) {
        return mPref.getInt(key.name(), 0);
    }

    public int getInt(Key key, int defaultValue) {
        return mPref.getInt(key.name(), defaultValue);
    }

    public long getLong(Key key) {
        return mPref.getLong(key.name(), 0);
    }

    public long getLong(Key key, long defaultValue) {
        return mPref.getLong(key.name(), defaultValue);
    }

    public float getFloat(Key key) {
        return mPref.getFloat(key.name(), 0);
    }

    public float getFloat(Key key, float defaultValue) {
        return mPref.getFloat(key.name(), defaultValue);
    }

    /**
     * Convenience method for retrieving doubles.
     * <p/>
     * There may be instances where the accuracy of a double is desired.
     * SharedPreferences does not handle doubles so they have to
     * cast to and from String.
     *
     * @param key The enum of the preference to fetch.
     */
    public double getDouble(Key key) {
        return getDouble(key, 0);
    }

    /**
     * Convenience method for retrieving doubles.
     * <p/>
     * There may be instances where the accuracy of a double is desired.
     * SharedPreferences does not handle doubles so they have to
     * cast to and from String.
     *
     * @param key The enum of the preference to fetch.
     */
    public double getDouble(Key key, double defaultValue) {
        try {
            String string = mPref.getString(key.name(), String.valueOf(defaultValue));
            if (string == null) {
                return defaultValue;
            }
            return Double.valueOf(string);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public boolean getBoolean(Key key, boolean defaultValue) {
        return mPref.getBoolean(key.name(), defaultValue);
    }

    public boolean getBoolean(Key key) {
        return mPref.getBoolean(key.name(), false);
    }

    public Set<String> getSet(Key key) {
        return mPref.getStringSet(key.name(), new HashSet<>());
    }

    /**
     * Remove keys from SharedPreferences.
     *
     * @param keys The enum of the key(s) to be removed.
     */
    public void remove(Key... keys) {
        doEdit();
        for (Key key : keys) {
            mEditor.remove(key.name());
        }
        doCommit();
    }

    /**
     * Remove all keys from SharedPreferences.
     */
    public void clear() {
        doEdit();
        mEditor.clear();
        doCommit();
    }

    public boolean isLoggedIn() {
        return getString(Key.TOKEN_STR) != null;
    }

    public void edit() {
        mBulkUpdate = true;
        mEditor = mPref.edit();
    }

    public void commit() {
        mBulkUpdate = false;
        mEditor.commit();
        mEditor = null;
    }

    private void doEdit() {
        if (!mBulkUpdate && mEditor == null) {
            mEditor = mPref.edit();
        }
    }

    private void doCommit() {
        if (!mBulkUpdate && mEditor != null) {
            mEditor.commit();
            mEditor = null;
        }
    }
}

Вот как вы устанавливаете и получаете доступ к данным из LoginAppState формы Activity.

LoginAppState mLoginAppState = LoginAppState.getInstance(this);
mLoginAppStateput(LoginAppState.Key.NAME_STR,"Stuart DTO");
mLoginAppStateput(LoginAppState.Key.EMAIL_STR,"stauart@stackoverflow.com");

Для доступа к данным из LoginAppState из вашего Activity.

LoginAppState mLoginAppState = LoginAppState.getInstance(this);
mLoginAppState.getString(AppState.Key.NAME_STR,"defualt_value");
mLoginAppState.getString(AppState.Key.EMAIL_STR,"defualt_value");
0
Pavan Nagaraja 21 Дек 2019 в 05:38