简体   繁体   English

如何将(Android)应用程序上下文传递给Java类?

[英]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 . MyActivityonCreate中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android-如何从Java类传递另一个活动应用程序上下文将片段扩展到asynctask? - Android - How to pass another activity application context from java class extends fragments to asynctask? 如何使用 pyjnius 将 android 上下文传递到 java 构造函数 class 中? - How to pass android context into a java constructor class using pyjnius? 将活动上下文传递给Application类而不是上下文 - Pass Activity Context to the Application class instead of Context 如何将上下文从MainActivity传递到Android中的另一个类? - How to pass context from MainActivity to another class in Android? Android Studios如何将上下文从mainactivity传递到另一个类 - Android studios how to pass a context from mainactivity to another class 如何将正确的上下文传递给新的RelativeLayout? android java - How do i pass the correct context into new RelativeLayout? android java 在Java Android中的Application类和Activity之间传递数据 - Pass data between Application class and Activity in Java Android 在上下文中传递给 Java 类 - Android - Passing in context to a Java Class - Android Android / Java类的作用域和上下文 - Android / Java class scope and Context 如何在Java类中获取JSP应用程序上下文 - How to get JSP Application Context inside a java class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM