views:

912

answers:

4

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.

A: 

Maybe I'm not reading your question right, but you should be able to get system preferences static-ly using android.provider.Settings.System

Edit
I think I understand now.. no context means you have no ContentResolver. Have you tried passing null instead? Who knows ..

Matt
I've checked that. Crashes!
Mostafa
+2  A: 

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.

Klondike
No, it's not about laziness. I'm customizing whole the Android, and this class is called by an internal Android class that doesn't have context.
Mostafa
Then Preferences aren't what you want to use to store the information. Preferences are scoped to applications/activities. Store the information on disk instead.
Klondike
Thanks. That may help. I should check.
Mostafa
A: 

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.

haseman
A: 

You can create a context:

Context myContext = createPackageContext("com.example", 0);
kuester2000
Please add comments, when you downvote this answer. So we can learn why this is not a good solution.
kuester2000