Tuesday, 3 June 2014

Uri from local drawables for universal image loader

Here is short example how display local drawables by universal image loader.

We have somewhere xml, array with images:

 <array name="avatars_male">  
      <item>@drawable/pic0</item>  
      <item>@drawable/pic1</item>  
      <item>@drawable/pic2</item>  
      <item>@drawable/pic3</item>  
      <item>@drawable/pic4</item>  
      <item>@drawable/pic5</item>  
      <item>@drawable/pic6</item>  
      <item>@drawable/pic7</item>  
      <item>@drawable/pic8</item>  
      <item>@drawable/pic9</item>  
      <item>@drawable/pic10</item>  
      <item>@drawable/pic11</item>  
      <item>@drawable/pic12</item>  
      <item>@drawable/pic13</item>  
 </array>  

We can load them to list:

 ArrayList<Integer> array = new ArrayList<Integer>();  
 TypedArray typedArray = getResources().obtainTypedArray(R.id.avatars_male);  
 for (int i = 0; i < 15; i++) {  
      array.add(typedArray.getResourceId(i, 0));  
 }  

And now we can take any pic by uri:

 int num = 10;//<according to value from dice :)  
   
 Uri uri = Uri.parse("drawable://" + array.get(num));  

Few configs how to prepare universal image loader:

 ImageLoaderConfiguration configBuilder = new ImageLoaderConfiguration.Builder(context)  
           .threadPriority(Thread.NORM_PRIORITY - 2)  
           .discCacheExtraOptions(250, 250, Bitmap.CompressFormat.JPEG, 75, null).build();  
   
 ImageLoader imageLoader = ImageLoader.getInstance();  
 imageLoader.init(configBuilder);  
   
 DisplayImageOptions imageLoaderOptions = new DisplayImageOptions.Builder()  
           .cacheInMemory(true) // default  
           .cacheOnDisc(true) // default  
           .imageScaleType(ImageScaleType.EXACTLY) // default  
           .bitmapConfig(Bitmap.Config.ARGB_8888) // default  
           .handler(new Handler()) // default  
           .build();  

And displaying:

 imageLoader.displayImage(String.valueOf(uri), holder.iv, imageLoaderOptions);