Java Can';无法访问扩展应用程序的类中的SharedReference
我试图通过扩展Java Can';无法访问扩展应用程序的类中的SharedReference,java,android,Java,Android,我试图通过扩展应用程序类来编写全局方法。 具体来说,我尝试添加2个方法来快速访问存储在SharedReferences中的一个值。 不幸的是,我无法使SharedReferences工作,以下是代码: package postfixcalculator.mattiarubini.com.postfixcalculator; import android.app.Application; import android.content.Context; import android.content
应用程序
类来编写全局方法。
具体来说,我尝试添加2个方法来快速访问存储在SharedReferences
中的一个值。
不幸的是,我无法使SharedReferences
工作,以下是代码:
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()
在活动中不起作用,但在片段中,我不知道在这种特殊情况下该怎么办。
通常在活动
中,为了使共享参考
有效,我只需要使用关键字this
以下是我得到的错误:
无法解析方法“getActivity()”
无法解析方法“getPreferences(int)”
尝试使用getApplicationContext()而不是getActivity()。尝试使用GetSharedReferences()的getApplicationContext()
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences .edit();
editor.putBoolean(getString(R.string.purchase_status), flag);
editor.commit();
请尝试保存共享首选项:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.edit().putString("key","value").apply();
要获取共享首选项值,请执行以下操作:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
sharedPreferences.getString("key","");
我希望这会有所帮助。我使用getSharedReferences(“首选项名称”,Context.MODE\u PRIVATE)代码>在我的应用程序类中。您认为您正在进行哪些活动?如果没有活动怎么办?您应该从上下文中获取首选项
我尝试传递上下文,但它不起作用编辑不起作用,问题转移,我得到错误:无法解析方法“getPreferences(int)”它不起作用我得到错误:无法解析符号“SharedPreferences”您必须声明变量。SharedReferences SharedReferences谢谢,您的解决方案确实有效,但我更倾向于使用另一个。欢迎:)