[英]How to pass (Android) application context to a Java class?
I have the following code in which I am using the application context to retrieve needed information: 我有以下代码,我使用应用程序上下文来检索所需的信息:
public class Data{
private boolean VarA;
public void setVarA(boolean B,Context ctx)
{
SharedPreferences CoreDataStorage = ctx.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = CoreDataStorage.edit();
editor.putBoolean("PrefVarA", VarA);
edit.commit();
}
}
Now I am calling the public method setVarA() from the below class 现在我从下面的类调用公共方法setVarA()
public class MyActivity extends Activity{
Data cd = new Data();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
cd.setVarA(true,this);
}
}
In the activity above it shows me compilation error that it can't cast from MyActivity to Context. 在上面的活动中,它向我显示了无法从MyActivity转换为Context的编译错误。 Please suggest any solution. 请建议任何解决方案。 Is the above code is not proper way to pass the context? 上面的代码是不是传递上下文的正确方法?
You need the application Context to access the shared preferences. 您需要应用程序Context才能访问共享首选项。 It should be: 它应该是:
cd.setVarA(true,this.getApplicationContext());
in the onCreate
of MyActivity
. 在MyActivity
的onCreate
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.