Search code examples
androidandroid-widget

Saving data for widget


I created RSS widget that fetches data on onUpdate and saves it in an ArrayList of article objects. Each Object class look like so:

public class Story {
    private String title;
    private String link;
    private Date pubDate;
    private String imgUrl;
    private Bitmap img;
    private String content;
}

It holds the data and as well the image in Bitmap format (very small images). The widget works like so, on pressing right and left buttons on widget it cycles between stories from an ArrayList. I can see that the data holds about 12-24 hours in the ArrayList, and then the widget is not working anymore.

  1. What is the best way to store data for widget like this?
  2. What is a life expectancy for global variables in widget?

Solution

  • When you retrieve the data (which includes the Bitmap you need), encode your Bitmap to String, then put the String inside SharedPreferences.

    You will want to change your image loading approach, where you get the String from the SharedPreferences first, decode it into Bitmap (if it is not null or empty), then put it inside your ImageView.

    This is a useful source to encode/decode Bitmap to String (and vice versa):

    How many ways to convert bitmap to string and vice-versa?

    Note: This is quite effective under the condition where the size of the Bitmap is really small. Otherwise, you need to use something like Glide or Picasso to help you with Bitmap caching.