【问题标题】:What context to use with shared preferences in another class?在另一个类中与共享首选项一起使用什么上下文?
【发布时间】:2016-12-16 13:11:17
【问题描述】:

我不知道如何在另一个不是片段或任何东西的类中使用共享首选项

这是我的主要活动代码:

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 内容时,该代码可以完美运行。

【问题讨论】:

  • 在您分配sharedPref 时,contextnull。将sharedPrefeditor的赋值移到构造函数中

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


【解决方案1】:

这是用于 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")

您可以在应用程序的任何地方使用。

【讨论】:

    【解决方案2】:

    您在收到 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】:

    移动你的代码

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

    因为它的首字母在这里。在此之前它是空的。

    【讨论】:

    • 我。试试看,构造函数仍然被调用第二个。放置成员变量的位置无关紧要。
    • 这是我的打字错误!
    【解决方案4】:

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

    this.context = context.getApplicationContext();
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      相关资源
      最近更新 更多