Calling SharedPreferences on AppWidget
I would like to know if there is an issue with calling a sharedPreference value on an appWidget provider class so i can use it for an update. I have this code which i call on a method in the appWidget provider class, but it keeps giving me compilation error and that i should create a method for it. this is the code:
prefs = getSharedPreference("myPrefs", Context.MODE_PRIVATE);
is this 开发者_如何转开发a known issue and is there any other way i can pass the value from my configuration class, if this is not possible.
AppWidgetProvider
s are not Context
s, and therefore do not have access to getSharedPreferences()
.
There is a standard way to set preferences for AppWidgets, however, which is documented on the Android developer site: http://developer.android.com/guide/topics/appwidgets/index.html#Configuring
The basic idea is that you tell the system to launch an activity when the user indicates they want to configure your widget. The configuration screen is obviously an Activity
, so it has access to SharedPreferences
, among other things. You then do all your configuring there and manually update the AppWidget
, whose ID was passed in the start Intent
. Definitely take a look at the link above to see the detailed steps needed.
Also see http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/appwidget/ExampleAppWidgetConfigure.html for an actual source code example.
It sounds like you are not initializing it using Context. Calling getSharedPreference
assumes this.getSharedPreference
which might not be correct.
What class are you calling this within and perhaps you could provide some more source code.
If I were to guess however I would say you could fix is like this:
prefs = getContext().getSharedPreference("myPrefs", Context.MODE_PRIVATE);
or perhaps:
prefs = getApplicationContext().getSharedPreference("myPrefs", Context.MODE_PRIVATE);
or if you have access to a View class:
prefs = view.getContext().getSharedPreference("myPrefs", Context.MODE_PRIVATE);
精彩评论