Какой контекст использовать с общими настройками в другом классе?

Я не могу понять, как использовать общие настройки в другом классе, который не является фрагментом или чем-то еще.

Вот мой основной код активности:

public class MainActivity extends AppCompatActivity {

    Backgrounds backs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        backs = new Backgrounds(this);
        bg = (LinearLayout) findViewById(R.id.background);
        bg.setBackgroundColor(getResources().getColor(backs.getBackground()));
        }
}

А вот мой класс Backgrounds:

public class Backgrounds {
    Integer colors[] = {
            R.color.red,
            R.color.pink,
            R.color.purple,
    };

    private context;
    SharedPreferences sharedPref = context.getSharedPreferences("file", 0);
    SharedPreferences.Editor editor = sharedPref.edit();
    int i = sharedPref.getInt("background", -1);
    public Backgrounds(Context context)
    {
        this.context = context
    }
    public int getBackground()
    {
        i++;
        try{
            editor.putInt("factIndex", i);
            editor.commit();
            return colors[i];
        }catch (Exception e){
            i = 0;
            editor.putInt("factIndex", i);
            editor.commit();
            return colors[i];
        }
    }
}

Я пробовал это многими способами. Я почти уверен, что это проблема с контекстной частью кода, поскольку я получаю эту ошибку:

Вызвано: java.lang.NullPointerException: попытка вызвать виртуальный метод «android.content.SharedPreferences android.content.Context.getSharedPreferences (java.lang.String, int)» для нулевой ссылки на объект

Я также пробовал использовать context.getApplicationContext(), но ошибка была похожей. Я подумал, что это может быть из-за того, что мне нужно было переместить назначение объекта Backs в onCreate(), но это все еще не работает. Я очистил проект и синхронизировал файлы с помощью gradle, но программа все равно вылетает до загрузки. Код отлично работает при удалении любых материалов SharedPrefrances.


person John O'Neil    schedule 16.12.2016    source источник
comment
В момент, когда вы назначаете sharedPref, context становится null. Переместите назначение sharedPref и editor в конструктор   -  person Bene    schedule 16.12.2016


Ответы (4)


Вы используете context перед тем, как получить его, значит, внешний конструктор или сказать, прежде чем конструктор будет выполнен, поэтому сделайте это как

    SharedPreferences sharedPref ;
    SharedPreferences.Editor editor;
    int i = sharedPref.getInt("background", -1);

    // before this , you cannot use the context reference ,it will be null
    public Backgrounds(Context context)
    {
       this.context = context
       // receive the context here and now you can safely use it
       sharedPref = context.getSharedPreferences("file", 0)
       editor = sharedPref.edit() 
  } 
person Pavneet_Singh    schedule 16.12.2016
comment
Спасибо. Это работает, хотя те, кто рекомендует помещать определения после конструктора, не работают. - person John O'Neil; 16.12.2016

Это для общего класса для предпочтений.

public class Preference {
    private final static String PREF_FILE = "PREF";

    /**
     * Set a string shared preference
     *
     * @param key   - Key to set shared preference
     * @param value - Value for the key
     */
    public static void setSharedPreferenceString(Context context, String key, String value) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(key, value);
        editor.apply();
    }

    /**
     * Set a integer shared preference
     *
     * @param key   - Key to set shared preference
     * @param value - Value for the key
     */
    public static void setSharedPreferenceInt(Context context, String key, int value) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    /**
     * Set a Boolean shared preference
     *
     * @param key   - Key to set shared preference
     * @param value - Value for the key
     */
    public static void setSharedPreferenceBoolean(Context context, String key, boolean value) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    /**
     * Get a string shared preference
     *
     * @param key      - Key to look up in shared preferences.
     * @param defValue - Default value to be returned if shared preference isn't found.
     * @return value - String containing value of the shared preference if found.
     */
    public static String getSharedPreferenceString(Context context, String key, String defValue) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        return settings.getString(key, defValue);
    }

    /**
     * Get a integer shared preference
     *
     * @param key      - Key to look up in shared preferences.
     * @param defValue - Default value to be returned if shared preference isn't found.
     * @return value - String containing value of the shared preference if found.
     */
    public static int getSharedPreferenceInt(Context context, String key, int defValue) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        return settings.getInt(key, defValue);
    }

    /**
     * Get a boolean shared preference
     *
     * @param key      - Key to look up in shared preferences.
     * @param defValue - Default value to be returned if shared preference isn't found.
     * @return value - String containing value of the shared preference if found.
     */
    public static boolean getSharedPreferenceBoolean(Context context, String key, boolean defValue) {
        SharedPreferences settings = context.getSharedPreferences(PREF_FILE, 0);
        return settings.getBoolean(key, defValue);
    }
}

это используется для настройки Получить и установить

Preference.setSharedPreferenceString(this, "Key", "Value")
Preference.getSharedPreferenceString(this, "Key", "default_Value")

Вы можете использовать в любом месте приложения.

person Shanmugavel GK    schedule 16.12.2016

Переместите этот код

SharedPreferences sharedPref = context.getSharedPreferences("file", 0);
SharedPreferences.Editor editor = sharedPref.edit();

после

SharedPreferences sharedPref;
SharedPreferences.Editor editor
public Backgrounds(Context context)
{
    this.context = context
    sharedPref = context.getSharedPreferences("file", 0);
    editor = sharedPref.edit();
}

потому что его инициалы здесь. до этого он нулевой.

person Piyush    schedule 16.12.2016
comment
Мне. Попробуйте, конструктор по-прежнему вызывается вторым. Неважно, где вы размещаете переменные-члены. - person Bene; 16.12.2016
comment
Это была моя опечатка! - person Piyush; 16.12.2016

Не сохраняйте Context как поле, это может привести к утечке памяти. Лучше всего, как @Shanmugavel GK написал ниже, создать статические методы или хотя бы сделать

this.context = context.getApplicationContext();
person Alexander Pereverzev    schedule 16.12.2016