Reputation: 28086
In an Android utility class, I want to get a system preference value in a class, but I don't have the context there, because the class that calls it doesn't have the context either. I've found that for Resources one can use the static Resources.getSystem()
function. Is there any similar way for getting system preferences without context?
My class isn't an activity nor service. It's a utility class. Could give more info if needed.
Upvotes: 12
Views: 7297
Reputation: 6957
You can create a context:
Context myContext = createPackageContext("com.example", 0);
Upvotes: -2
Reputation: 11313
I use the following Hack: http://www.hasemanonmobile.com/2009/10/05/quick-and-very-dirty-android-development-trick/
Essentially you stash off a context pointer as a static variable inside your Activity. I'd only recommend this ugly hack if you're on a tight deadline.
Further, if you're writing a utility class, you should probably require (as many Android utilities require) that the calling application provide you with a context as part of your constructor.
Upvotes: -1
Reputation: 3495
You've got to send it a Context - don't try to run away from your responsibilities. :) Your utility class must be getting called by an Activity or Service at some level, and you're going to have pass that Context all the way down the line, through every method call. I know it's annoying, I've had to do similar things myself. Consider it an incentive to keep your code simple and to require as few method calls possible to get something accomplished.
Upvotes: 7