Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Widget Configuration with SharedPreferences

i want to let the user define a username when starting a homescreen widget im working on. But im having troubles with storing and accessing this value in my widget. What i do at the moment is creating a Configuration Activity which gets started when the widget is created. Therefore i defined it in the manifest file as follows (i also defined it in the widgetprovider.xml):

    <activity android:name=".ExampleAppWidgetConfigure">
       <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
       </intent-filter>
    </activity>

The Configuration Activity then allows the user to enter a username which will be stored in the SharedPreferences of the Widget:

    SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, MODE_WORLD_READABLE).edit();
    prefs.putString("username", text);
    prefs.commit();

My question is how do i access this value? In my widget class i want to have an instance variable like:

final String userName = ...; //load the username here.

But how do i retrieve the username in my widget? The problem is the widget is a subclass of AppWidgetProvider from which i can't access the SharedPreferences (because AppWidgetProvider is not a subclass of Context). I thought about storing the username in the strings.xml file which also doesnt seem to be possible. Is using SharedPreferences the right way at all? I also thought about setting the username to a TextView of my widget, which is later on supposed to display the username. But i need the username in my class for some server requests and it seems there is no way to get the text of a TextView in a widget...only the setter setTextViewText(String text) is defined.

How can i retrieve the username?

like image 740
gaussd Avatar asked Mar 03 '11 17:03

gaussd


1 Answers

You need to obtain the SharedPreferences instance from the context, which is provided in the onUpdate() method in the widget provider. Something like this:

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0);
}
like image 125
chrispr Avatar answered Sep 22 '22 02:09

chrispr