1

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

Вот мой основной код деятельности:

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())); 
     } 
} 

А вот мой класс обои:

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(), но ошибка была аналогичной. Я подумал, что это может быть потому, что мне нужно было переместить assinging объекта Backs в onCreate(), но это все еще не работает. Я очистил проект и синхронизирул файлы с помощью градиента, но программа все равно вылетает до загрузки. Код отлично работает при удалении любого материала SharedPrefrences.

+0

В точке вы назначаете 'sharedPref',' 'context' является null'. Переместите назначение 'sharedPref' и' editor' в конструктор – Bene

ответ

1

Вы используете 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() 
    } 
+1

Спасибо. Это работает, хотя те, кто рекомендует, чтобы я помещал определения после того, как конструктор не работает –

1

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

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(); 
} 

, потому что его парафирование здесь. перед этим он равен нулю.

+0

Me. Попробуйте, конструктор по-прежнему называется вторым. Неважно, где вы размещаете переменные-члены. – Bene

+0

Это была моя ошибка в типографии! – Piyush

3

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

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") 

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

1

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

this.context = context.getApplicationContext(); 
Смежные вопросы