Android batch image loading classic series-using xutil framework cache and asynchronously loading network images

Source: Internet
Author: User

Android batch image loading classic series-using xutil framework cache and asynchronously loading network images

I. Problem Description

To improve image loading efficiency, cache and asynchronous loading policies are required for images. The encoding is relatively complex. In fact, some excellent frameworks provide solutions, for example, the recently active xutil framework in git

  The Xutil framework provides four modules:

1. DbUtil module: The ORM mechanism is used to simplify Sqlite operations. One line of code can be used to add, delete, modify, query, support transactions, and support latency policies.

2. ViewUtils module: it can be called the IOC framework of Android, and can be annotated to bind the ui, resources, and events.

3. HttpUtils module: supports synchronous and asynchronous requests and large file uploads

4. BitmapUtils module: asynchronous image loading. It supports local and network images, image compression, image memory cache, and local file cache.

In this case, the HttpUtils module and BitmapUtils module of Xutil are used.

Ii. Case studies

Achieve Picture News browsing:

Iii. Main case Technologies
1. Use the HttpUtils module for network communication

(1) The RequestParams component sets request parameters, upload files, and other information.

 
RequestParams params = new RequestParams ("UTF-8"); // default encoding UTF-8 params. addQueryStringParameter (categoryId, 2); // set parameters

(2) The HttpUtils component sends a request

 
HttpUtils http = new HttpUtils (); http. configResponseTextCharset (UTF-8); // sets the encoding of the returned text, the default encoding UTF-8 // send the request, respectively set the transfer method, url, transfer data, callback component httpUtils. send (HttpMethod. POST, http: // 192.168.2.178: 8080/21-sun/PhotosServlet, params, new RequestCallBack
 
  
() {@ Override public void onFailure (HttpException e, String m) {// execution failure callback method Log. I (jereh, e. getExceptionCode () ++ m);} @ Overrid public void onSuccess (ResponseInfo
  
   
Info) {// callback Method for successful execution, and pass in data, get returned data through info. result }});
  
 
2. asynchronous loading of BitmapUtils Images

Asynchronous loading of BitmapUtils images supports local and network images and image compression.

(1) configuration of BitmapDisplayConfig Image Display

 
BitmapDisplayConfig bigPicDisplayConfig = new BitmapDisplayConfig (); // display the original image. Do not compress the image. Try not to use it. OOM is easy when the image is too large. BigPicDisplayConfig. setShowOriginal (true); bigPicDisplayConfig. setBitmapConfig (Bitmap. config. RGB_565); // sets the maximum image size. If this parameter is not set, displayConfig is more adaptive to the control attributes. setBitmapMaxSize (BitmapCommonUtils. getScreenSize (mActivity); // implements a gradient animation. AlphaAnimation animation = new AlphaAnimation (0.1f, 1.0f); animation. setDuration (500); displayConfig. setAnimation (animation );

(2) create BitmapUtils

Structure:

 
/*** @ Param context Context * @ param diskCachePath disk cache path * @ param memoryCacheSize memory cache size * @ param diskCacheSize disk cache space size */BitmapUtils (context, string diskCachePath, int memoryCacheSize, int diskCacheSize)

Other Forms

 
BitmapUtils(Context context) BitmapUtils(Context context, String diskCachePath) BitmapUtils(Context context, String diskCachePath, int memoryCachePercent);

Code:

 
// Obtain the maximum available memory of the application. int maxMemory = (int) Runtime. getRuntime (). maxMemory (); int cacheSize = maxMemory/8; FileUtils fileUtils = new FileUtils (mActivity, jereh); // sets the File Cache and memory cache size BitmapUtils utils = new BitmapUtils (mActivity, fileUtils. getCacheDir (), cacheSize );

(3) The display () method asynchronously loads images and displays them on the View control.

 
utils.display(T container , String uri, BitmapDisplayConfig displayConfig);
3. parse json data using the Gson component
 
Gson gson = new Gson (); // create the gson component // parse the JSON data returned by the server and use Gson to parse the List
 
  
ImageInfo = gson. fromJson ("JSON data", new TypeToken> () {}. getType ());
 
Iv. Complete case code
1. PhotoBrowseAdapter adapter code
 
Public class PhotoBrowseAdapter extends PagerAdapter {private Activity mActivity; private List
 
  
ImageList; private LayoutInflater inflate; private BitmapUtils utils; private BitmapDisplayConfig displayConfig; public PhotoBrowseAdapter (Activity mActivity, List
  
   
ImageList) {super (); this. mActivity = mActivity; this. imageList = imageList; inflate = LayoutInflater. from (mActivity); // get the maximum available memory of the application int maxMemory = (int) Runtime. getRuntime (). maxMemory (); int cacheSize = maxMemory/8; FileUtils fileUtils = new FileUtils (mActivity, jereh); utils = new BitmapUtils (mActivity, fileUtils. getCacheDir (), cacheSize); displayConfig = new BitmapDisplayConfig (); // displayConfig. se TShowOriginal (true); // display the original image. Do not compress it. Try not to use it. OOM is easy when the image is too large. // Utils. configDefaultBitmapMaxSize (BitmapCommonUtils. getScreenSize (mActivity); displayConfig. setBitmapMaxSize (BitmapCommonUtils. getScreenSize (mActivity); AlphaAnimation animation = new AlphaAnimation (0.1f, 1.0f); animation. setDuration (500); displayConfig. setAnimation (animation);} @ Override public int getCount () {// TODO Auto-generated method stub return imageList. size () ;}@ Override public boolean isViewFromObject (View arg0, Object arg1) {// TODO Auto-generated method stub return arg0 = arg1 ;} @ Override public Object instantiateItem (View container, int position) {ImageInfo info = imageList. get (position); LinearLayout view = (LinearLayout) inflate. inflate (R. layout. phone_item, null); (TextView) view. findViewById (R. id. tvTitle )). setText (info. getImgTitle (); (TextView) view. findViewById (R. id. tvContent )). setText (info. getImgDesc (); ImageView img = (ImageView) view. findViewById (R. id. ivPhoto); img. setTag (info. getImgUrl (); utils. display (img, info. getImgUrl (), displayConfig); (ViewPager) container ). addView (view); return view;} @ Override public void destroyItem (View container, int position, Object obj) {(ViewPager) container ). removeView (View) obj );}}
  
 
2. MainActivity code
 
Public class MainActivity extends Activity {private ViewPager vpImagePager; private PhotoBrowseAdapter adapter; private List
 
  
ImageInfoList; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); vpImagePager = (ViewPager) super. findViewById (R. id. vpImgBrowse); imageInfoList = new ArrayList
  
   
(); Adapter = new PhotoBrowseAdapter (this, imageInfoList); loadData ();} private void loadData () {RequestParams params = new RequestParams (); params. addQueryStringParameter (categoryId, 2); // set the parameter HttpUtils httpUtils = new HttpUtils (); // send the request httpUtils to the server. send (HttpMethod. POST, http: // 192.168.2.178: 8080/21-sun/PhotosServlet, params, new RequestCallBack
   
    
() {@ Override public void onFailure (HttpException e, String m) {Log. I (jereh, e. getExceptionCode () ++ m);} @ Override public void onSuccess (ResponseInfo
    
     
Info) {// callback after the background execution is complete, and pass in the returned data Gson gson = new Gson (); // create the gson component // set info. the result server returns JSON data and uses Gson to parse the List.
     
      
ImageInfo = gson. fromJson (info. result, new TypeToken> (){}. getType (); imageInfoList. addAll (imageInfo); vpImagePager. setAdapter (adapter );}});}}
     
    
   
  
 
3. ImageInfo object class and FileUtils tool class
 
// Encapsulate the image information public class ImageInfo {private String imgUrl; private String imgTitle; private String imgDesc ;... // Omitted} FileUtils obtains the File cache directory public class FileUtils {/** cache File directory */private File mCacheDir; public FileUtils (Context context, String cacheDir) {if (android. OS. environment. getExternalStorageState (). equals (android. OS. environment. MEDIA_MOUNTED) mCacheDir = new File (cacheDir); else mCacheDir = context. getCacheDir (); // how to obtain the built-in cache storage path if (! MCacheDir. exists () mCacheDir. mkdirs ();} public String getCacheDir () {return mCacheDir. getAbsolutePath ();}
4. Server PhotosServlet code
 
Public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType (text/json; charset = UTF-8); String categoryId = request. getParameter (categoryId); // test the passing parameter System. out. println (categoryId); List
 
  
PartList = new ArrayList
  
   
(); ImagePart part1 = new ImagePart (); part1.setImgUrl (http://news.21-sun.com/UserFiles/x_Image/x_20150216131001_0.jpg); part1.setImgTitle (representing China's Dongfeng team, come on !); Part1.setImgDesc (...); imagePart part2 = new ImagePart (); part2.setImgUrl (http://news.21-sun.com/UserFiles/x_Image/x_20150216131432_0.jpg); part2.setImgTitle (3awo sailing experience tour); part2.setImgDesc (...); imagePart part3 = new ImagePart (); part3.setImgUrl (http://news.21-sun.com/UserFiles/x_Image/x_20150216131157_0.jpg); part3.setImgTitle (CEO and CEO of Volvo Group ourov pesen and Volvo); part3.setImgDesc (...); partList. add (part1); partList. add (part2); partList. add (part3); JSONArray jsonArray = JSONArray. fromObject (partList, config); response. getWriter (). println (jsonArray. toString ());}
  
 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.