Android widget configuration with SharedPreferences

I want the user to determine the username when starting the desktop widget that he is working on. But I am having problems storing and accessing this value in my widgets. What I'm doing at the moment is creating a configuration activity that starts when the widget is created. Therefore, I defined it in the manifest file as follows (I also defined it in widgetprovider.xml):

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

Then, “Configuration Activity” allows the user to enter the username that will be stored in the SharedPreferences 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 of type:

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

But how can I get the username in my widget? The problem is that the widget is a subclass of AppWidgetProvider , from which I cannot access SharedPreferences (because AppWidgetProvider not a subclass of Context ). I was thinking about storing the username in the strings.xml file, which also seems impossible. Does SharedPreferences correct path? I also thought about setting the username in the TextView my widget, which should later display the username. But I need a username in my class for some server requests, and it seems that there is no way to get TextView text in widgets ... only setter setTextViewText(String text) defined.

How can I get the username?

+4
source share
1 answer

You need to get the SharedPreferences instance from the context that is provided in the onUpdate () method of the widget provider. Something like that:

  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME,0); } 
+7
source

Source: https://habr.com/ru/post/1342158/


All Articles