在另一个类中使用共享首选项的上下文是什么?

时间:2016-12-16 13:11:18

标签: java android android-studio sharedpreferences android-context

我无法解决如何在另一个不是片段或其他类的课程中使用共享偏好

这是我的主要活动代码:

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(),但错误类似。我想这可能是因为我需要将Backs对象的分配移动到onCreate()但仍然无法工作。我已经用gradle清理了项目和同步文件,但程序在加载之前仍然崩溃。删除任何SharedPrefrences时,代码都能正常工作。

4 个答案:

答案 0 :(得分:4)

这适用于Preference的Common类。

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

因为它在这里初始化。在此之前它是null。

答案 2 :(得分: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() 
  } 

答案 3 :(得分:1)

不要将 Context 保存为字段,这是潜在的内存泄漏。它是@Shanmugavel GK在下面写的最好的方法,创建静态方法或者至少制作

this.context = context.getApplicationContext();