Pull to refresh
1
0
Send message
Li Feng, chief designer at the China Academy of Space Technology's communication satellite division, said the technology BEING TESTED IN ORBIT RIGHT NOW is «in the latter stages of the proof-of-principle phase» with the goal of making it available in satellites «as quickly as possible.»
«Although it is difficult to do this, we have the confidence that we will succeed,» he said.
Взаимно :). Я написал свой ответ, а потом только увидел, Ваш второй ответ.
Отвечу сначала на второй вопрос: Как видно из кода в моем посте PreferencesHelper инициализируется с использованием контекста Application в методе onCreate наследника класса Application, а не Activity или фрагмента.

«Application.onCreate called when the application is starting, before any activity, service, or receiver objects (excluding content providers) have been created. »
и т.о. метод initInstance вызывается один раз и инициализирует static INSTANCE соответственно тоже один раз при старте процесса приложения.
Метод getInstance просто getter, предоставляющий доступ к INTANCE. Все время используется один и тот же SharedPreferences, который получен при старте приложения.
Небольшое дополнение.
Для классической реализации синглтон, конструктор private и чтобы избежать проблем добавить synchronized в метод getInstance
private PreferencesHelper() {
        this.mSharedPreferences = App.getSharedPreferences();
        this.mEditor = this.mSharedPreferences.edit();
    }

public static synchronized PreferencesHelper getInstance() {
        if(INSTANCE == null) {
            INSTANCE = new PreferencesHelper();
        }
        return INSTANCE;
    }


или что мне больше нравится, разделить метод getInstance на два метода initInstance и getInstance:
public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        PreferencesHelper.initInstance(this);
    }
    
}

public class PreferencesHelper {
    private static PreferencesHelper INSTANCE = null;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;

    public static void initInstance(Conext context) {
            INSTANCE = new PreferencesHelper(context);
    }

    public static PreferencesHelper getInstance() {
        return INSTANCE;
    }

    private PreferencesHelper(Conext context) {
        this.mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        this.mEditor = this.mSharedPreferences.edit();
    }

    //для примера сохранение данных в SharedPreferences
    public void saveStatusCheckbox(String name, boolean status){
        mEditor.putBoolean(name, status);
        mEditor.apply();
    }

    //для примера загрузка из данных из SharedPreferences
    public int loadStatusCheckbox(String name){
        return mSharedPreferences.getBoolean(name, false);
    }
}

Information

Rating
Does not participate
Registered
Activity