1

I am working on an Android home screen widget, which selects a random image url from an array of urls (obtained from firebase database), and displays that image. The widget updates every 30 minutes, and should, therefore, display a new image every 30 minutes or so.

I'm using Picasso to display the image from the url.

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

if (currentWidget.url.length() > 0) {
    final RoundCornersTransformation transformation = new RoundCornersTransformation(50, 0);
    Picasso.get().load(currentWidget.url).memoryPolicy(MemoryPolicy.NO_CACHE).transform(transformation).into(new Target()  {
        @Override
        public void onBitmapLoaded (final Bitmap bitmap, Picasso.LoadedFrom from){
            Log.d("PICASSO", "Bitmap Loaded");
            views.setImageViewBitmap(R.id.appwidget_image, bitmap);
        }

        @Override
        public void onBitmapFailed(Exception e, Drawable errorDrawable) {
            Log.d("PICASSO", "Bitmap Failed");
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            Log.d("PICASSO", "Bitmap Prepared");
        }
    });
}

I have tested the url, and it is updating regularly, and there is no logical error in the code, as the image is displayed sometimes. But, most of the times, even when the url updates and I get "Bitmap Loaded" in the console, the image in the widget does not update.

1 Answers1

1

Okay, so after 10 hours of searching I found the problem and a fix.

Basically, Picasso holds a weak reference to the target class and it gets "Garbage Collected". Because of this, the image never loads the FIRST TIME. Because I was choosing a random URL every time, the same URL was being chosen only some of the times, which explains why it only displayed the image sometimes, and not every time after the first time it failed.

I fixed it by finding a way to remove the target class. Here's the fixed code:

if (currentWidget.url.length() > 0) {
    final RoundCornersTransformation transformation = new RoundCornersTransformation(50, 0);
    Picasso.get().load(currentWidget.url).transform(transformation).into(views, R.id.appwidget_image, new int[] {appWidgetId});
}

Useful posts:

  1. onBitmapLoaded of Target object not called on first load
  2. https://stackoverflow.com/a/28335661/12029824