How to store data for a widget?

I am creating a widget and I need to save some data for it. I do not have an Activity widget, so I cannot use SharedPreferences . The data that I store is very small, but often available, so it would be superfluous to use a database for this. I was thinking about using simple files, but that doesn't seem like a good solution. Is there a way to store simple data for a widget?

+4
source share
2 answers

You don’t need Activity to save preferences, just Context . In your class that extends AppWidgetProvider , you should get the context in all relevant methods, such as onUpdate and onDeleted .

Then you can use the PreferenceManager to get the preference object and store what you need in it, for example:

 @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String value = prefs.getString("key-string", null); if(value != null) { // do stuff } } 

As a side note, you mention that you thought you were using files, but didn't want for performance reasons. SharedPreferences objects actually end up using simple files, they are just managed for you by Android. If you intend to access it often, you still need to be careful about performance. The same is true for SQLite DB, as these are just files.

+3
source

Those usual Widget methods contain context, that's true, but what if these contexts change? For example, for example, an application calls an action that listens on the widget with onReceive and stores data in this context, can it be read with another application action? - in a different context.

What if it is canceled by the application and receive it? - with actions not sure about widgets!

0
source

All Articles