How to pass (Android) application context to a Java class?

夙愿已清 提交于 2019-12-22 05:14:45

问题


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?


回答1:


You need the application Context to access the shared preferences. It should be:

cd.setVarA(true,this.getApplicationContext());

in the onCreate of MyActivity.



来源:https://stackoverflow.com/questions/9240413/how-to-pass-android-application-context-to-a-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!