Reputation: 885
Assume, widget uses login and password to retrieve some data. I store login and pws in sharedPreferences.
Everything works fine as long as I have 1 widget. When I add the second widget login and pwd in sharedPreferences replaced for both widgets.
What is the typical solution for this problem>
Upvotes: 0
Views: 137
Reputation: 40203
In a usual case, the unique identifier for an AppWidget is an appWidgetId. So you can organize your preferences this way.
Assume you have a key for storing a login:
public static final String PREFS_LOGIN = "com.example.prefs.LOGIN";
And two methods to store the value and to retrieve it:
public void setLogin(String login) {
prefs.edit().putString(PREFS_LOGIN, login).commit();
}
public String getLogin() {
return prefs.getString(PREFS_LOGIN, "");
}
To ensure that preferences store login values for each appWidgetId and retrieve the correct one you can pass appWidgetId to these methods:
public void setLogin(String login, int appWidgetId) {
prefs.edit().putString(PREFS_LOGIN + appWidgetId, login).commit();
}
public String getLogin(int appWidgetId) {
return prefs.getString(PREFS_LOGIN + appWidgetId, "");
}
Hope this helps.
Upvotes: 1