Reputation: 6778
I have a problem in the LiveWallpaper app (my first) I am developing.
Consider 2 classes: LiveWallpaperService
and LiveWallpaperSettings
.
LiveWallpaperSettings
extends PreferencyActivity
. Example data representing
the preferences selected by the user, for example a boolean displaySprite
(true=> display the sprite on the screen, false do not display) are saved/persisted via SharedPreferences
in LiveWallpaperSettings
.
Upon starting the application (Settings -> Display -> LiveWallpaper -> MyLiveWallpaper), the saved preferences need to be known so that the sprite can be displayed or not.
However, LiveWallpaperSettings
is not instantiated until the Settings button is clicked, so SharedPreferences
is not available, and thus saved settings are unavailable until then.
I tried this in LiveWallpaperService.onCreateScene()
, but it has no data in it:
SharedPreferences startupPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
What can I do?
Upvotes: 0
Views: 166
Reputation: 18151
In your preferences xml set the default value and in your MainActivity onCreate() add the following code setDefaultValues(this, R.xml.yourxmlname, false);
Upvotes: 0
Reputation: 3546
There is a default value if the entry/sharedpref file does not exist:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
boolean display = settings.getBoolean("display", true);
"public abstract boolean getBoolean (String key, boolean defValue)"
Added in API level 1 Retrieve a boolean value from the preferences.
Parameters
key
The name of the preference to retrieve.
defValue
Value to return if this preference does not exist.
Hope I didnt misunderstood your question :)
Upvotes: 1