6

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 Answer 1

10

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

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

in the onCreate of MyActivity.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.