Search code examples
androidpreferences

Access application context in a storage class in Android


I have an app on Android 4.0. It uses the PreferenceManager class to -- among other things -- let the user specify how many decimal places of a number to show.

mPreferences = PreferenceManager.getDefaultSharedPreferences(this);

Generally I have no problem getting the app context in order to access the Preference Manager. My problem is that I have a class (let's call it Record) that isn't subclassing anything that has the app context; it's just a storage class, but it does have a field "NumDecPlaces". Right now, when I instantiate the class from within my app I just pass in the user's #dec places preference. It would be nice if Record could access the Preference manager directly. I suppose I could always instantiate Record with a pointer to the context from which it was created, but that's a lot to remember ;-)

So right now Record subclasses nothing. Any recommendations on what I can do to it to allow it to see the app context?

Thanks!


Solution

  • You could pass the Context object in the constructor. So whenever you try to use that class it will ask you pass a Context object and then use that to get SharedPreferences

    For eg.

    public Record(Context context)
    {
      mContext = context;
    
      mPreferences = PreferenceManager.getDefaultSharedPreferences(mContext)
    }