无法访问扩展Application的类中的SharedPreferences

时间:2017-04-14 11:02:52

标签: java android

我正在尝试通过扩展Application类来编写全局方法。 具体来说,我正在尝试添加2方法来快速访问存储在SharedPreferences中的一个值。 不幸的是我无法使SharedPreferences工作,这是代码:

package postfixcalculator.mattiarubini.com.postfixcalculator;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

public class PostfixCalculatorExtendApplication extends Application {

    public void ChangePreference (boolean flag){
        //I'm updating the preference file based on the purchase
        SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean(getString(R.string.purchase_status), flag);
        editor.commit();
    }

    public boolean RetrievePreferences (){
        SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        /*If the file doesn't exist, I create the file and I'm returned with a false value.
        * Because if the file was not created it's likely to be the first install.
        * If the user acquired the product on the store, it will be able to restore its purchase.*/
        boolean flagPurchase = sharedPref.getBoolean(getString(R.string.purchase_status), false);
        return flagPurchase;
    }
}

我理解getActivity()Activity中不起作用,但在Fragment中,我只是不知道在这个特定情况下该怎么做。 通常在Activity中,为了使SharedPreferences有效,我只需要使用关键字this

这些是我得到的错误:

  

无法解析方法'getActivity()'

     

无法解析方法'getPreferences(int)'

5 个答案:

答案 0 :(得分:1)

使用getSharedPreferences()

尝试getApplicationContext()

答案 1 :(得分:1)

使用

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

  SharedPreferences.Editor editor = preferences .edit();
  editor.putBoolean(getString(R.string.purchase_status), flag);
  editor.commit();

答案 2 :(得分:1)

我在我的Application类中使用getSharedPreferences("Name of preferences", Context.MODE_PRIVATE);

答案 3 :(得分:0)

尝试使用getApplicationContext()而不是getActivity()。

答案 4 :(得分:-1)

尝试此操作以保存共享首选项:

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putString("key","value").apply();

获取共享偏好值:

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.getString("key","");

我希望这会有所帮助。