android - Accessing SharedPreferences through static methods -


Some information is shared with me I need to exclude that activity from any activity (from a domain model class) ) That's why I have made a steady method in such an activity that I use to achieve shared preferences.

This is giving me some problems, because apparently it's not possible to call the "getsharedPreferences" method with a static method.

Here the message is given to me:

  Static references can not be obtained for non-static methods. GetSharedPreferences (string, int) from context type ContextWrapper  

I tried to work around it using an activity example, like this:

  public static shared options received preview () {Activity act = new activity (); Return Act Shared references ("FILE", 0); }  

This code gives an empty point exception.

Is there a work-around? Am I going to do an Android-code-odor trying to do this?

Thanks in advance.

That's because in this case, verb is an object which you Now you have to make Android do this for you; There is a method of getSharedPreferences () context ( activity , service and other classes context ). Therefore, you have to make your choice:

  • If the method is within an activity or other type of reference:

      getApplicationContext (). GetSharedPreferences ("Foo", 0);  
  • If the method is outside of an activity or other type of reference:

      // You must pass the reference to it . In your case: // it is within the public stable common elements of the public square. Share Reference (Reference CTX) {return ctxt.getSharedPreferences ("FILE", 0); } // And, this is your activity in YourClass.this.getSharedPreferences (YourClass.this.getApplicationContext ());  

Comments