Search code examples
androidandroid-widgetuniversal-image-loaderremoteview

Universal Image Loader inside RemoteViewsFactory for Android widget


I would like to publish a solution to a problem. Hopefully it will help other people facing the same problem.

This is related to the Android Universal Image Loader library available here

Original question was :

I started today to use your Android Universal Image Loader (AUIL) which is very very nice ! Thank you for sharing this !

I know that it is possible to use AUIL in an android widget project inside the Provider class but I'm trying to load multiples image inside a ListView (itself inside the widget).


Solution

  • The solution I manage to find is

    public class YourViewsFactory implements RemoteViewsService.RemoteViewsFactory
    {
     Map<Integer, Boolean> flags = Collections.synchronizedMap(new HashMap<Integer, Boolean>());
     Bitmap mBitmap;
     Handler handler = new Handler(Looper.getMainLooper());
    
    
      @Override
      public RemoteViews getViewAt(final int position)
    {
      final RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.row);
      flags.put(position, false);
      handler.post(new Runnable()
      {
        @Override
        public void run()
        {
            m_imgLoader.loadImage(YOUR_IMAGE_URL, new SimpleImageLoadingListener()
            {
                @Override
                public void onLoadingStarted(String imageUri, View view)
                {
                }
    
                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason)
                {
                    flags.put(position, true);
                }
    
                @Override
                public void onLoadingCancelled(String imageUri, View view)
                {
                    flags.put(position, true);
                }
    
                @Override
                public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap)
                {
                    mBitmap = bitmap;
                    flags.put(position, true);
                }
            });
        }
    });
    
    while (!flags.get(position))
    {
        try
        {
            Thread.sleep(100);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
    flags.put(position, false);
    if (mBitmap != null)
    {
        row.setImageViewBitmap(R.id.ivPoster, mBitmap);
    } else
    {
        row.setImageViewResource(R.id.ivPoster, R.drawable.cw);
    }
    mBitmap = null;
      } // End of getViewAt override
    
    
    } // End of class
    

    This is not my solution, but one of Vova Klyshevich available here!