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!

有帮助吗?

解决方案

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)
}

其他提示

You can also extend a class with Application, which will be global to the whole application and you can set the context in that class as a member variable and that context will be global to the whole application

Eg. class A extends Application{......}

You can do @Apoorv's suggestion or you can create another class that specifically stores the application context.

public class ContextResolver {

    private static Context context;

    public static void setContext(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("Context must not be null");
        } else if (context instanceof android.app.Activity) {
            context = androidContext.getApplicationContext();
        } else if (context instanceof android.content.Context) {
            context = androidContext;
        }
    }
    public Context getContext() {
       return context;
    }
}

Now you need to call setContext() in the first activity that will be launched once.

public class MyFirstActivity extends Activity {
    public void onCreate() {
         ContextResolver.setContext(this);
    }
}

Now you can retrieve the Context from any part of your code. So in your Record class you can just do this:

mPreferences = PreferenceManager.getDefaultSharedPreferences(ContextResolver.getContext());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top