tags:

views:

176

answers:

4

Hello, i'm using PreferenceActivity class to configure my widget. PreferenceActivity class automatically saves user preferences, so in widget update service i can call context.getSharedPreferences() and i obtain user preferences. Problem is follow: if you have many widget of same type, how PreferenceActivity class saves prefs? how i can load appWidgetId specific prefs from sharedPreferences?

A: 

I'm not entirely clear on what you're trying to do, but I'll take a stab at it. You use the id of your resource specified in the xml to call findPreference(CharSequence key).

Neil D
A: 

Specify an android:key attribute in the XML for your preference:

<CheckBoxPreference
    android:key="PREFS_KEY_DATA_3G"
    android:title="Data Over 3G/4G"
    android:summary="Allows use of cell network for gameplay. Uncheck for WiFi only. (Takes effect on next restart)."
    android:defaultValue="true"
    android:order="2"
    />

and the following code will retrieve the preference. I have this in a subclass of Application, but it should also work when called from an Activity or a Service. Just pass in an instance of Context to getDefaultSharedPreferences:

/**
 * Returns preference value for 3G data.
 * True == use 3G.
 * 
 * @return
 */
public boolean prefs3GEnabled() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    return prefs.getBoolean( "PREFS_KEY_DATA_3G", true );
}
mportuesisf
Premier is asking for different values for different widget instances.
Vitaly Polonetsky
A: 

One way of handling multiple widgets of the same type is to add the appWidgetId to the key when storing the prefs and add it to the key when retrieving the prefs.

If you need more info and code samples, let me know in the comments.

Vitaly Polonetsky
A: 

For AppWidgets and preferences I really liked this tutorial

http://www.helloandroid.com/tutorials/mastering-android-widget-development-part1

replace the one at the end by a 2 and by a 3 to get the continuation [I cannot post more links since I am a new user].

They give a tutorial where a preference is saved for jointly with the appwidget ID and it is shown how it is retrieved for updating the individual widgets.

thomasd