我试图通过扩展Application
类来编写全局方法。 具体地说我想要添加2方法来快速访问存储在SharedPreferences
一个值。 可惜我不能让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()
Cannot resolve method 'getActivity()'
Cannot resolve method 'getPreferences(int)'
你觉得哪个活动你得到婷?如果没有活动会怎么样? –
你应该从'Context' –
我试图通过上下文得到的喜好,并没有工作 –