如何将(Android)应用程序上下文传递给Java类?
我有以下代码,其中使用应用程序上下文来检索所需的信息:
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();
}
}
现在我从下面的类中调用公共方法 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);
}
}
在上面的活动中,它向我显示编译错误,它无法从 MyActivity 转换为语境。请提出任何解决方案。上面的代码不是传递上下文的正确方法吗?
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
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. Please suggest any solution. Is the above code is not proper way to pass the context?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要应用程序上下文来访问共享首选项。它应该是:
在
MyActivity
的onCreate
中。You need the application Context to access the shared preferences. It should be:
in the
onCreate
ofMyActivity
.