Implementation of Android Photo wall

Source: Internet
Author: User

Reprinted from http://blog.csdn.net/guolin_blog/article/details/9526203

Because each Android application has a memory limit, if you load a lot of pictures, there will be an Oom exception

This requires the use of LRUCache memory caching technology, LRUCache is in the Support-v4 jar package, so you want to use this technology to add the jar package.

The technical principle of LRUCache. Recently used objects are saved in Linkedhashmap with strong references, and removed from memory for those that are seldom used before the cache value reaches a predetermined value

The previously used soft references are no longer recommended after 2.3, because the Android garbage collection mechanism prefers to recycle soft references, making this technology no longer available

Package Com.qunzheng.photowalldemo;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.util.log;import Android.view.View; Import Android.view.viewgroup;import Android.widget.abslistview;import Android.widget.arrayadapter;import Android.widget.gridview;import Android.widget.imageview;import Java.io.inputstream;import Java.net.httpurlconnection;import java.net.url;import java.util.arraylist;import java.util.List;/** * Created by Qunzheng on 2015/5/17. */public class Photowalladapter extends Arrayadapter implements Abslistview.onscrolllistener {private static final Str    ing TAG = "photowalladapter";    Private GridView Mphotowall;    Define memory cache private Mylrucache memorycache;    private list<downloadbitmaptask> tasks;    private int firstvisibleitem;    private int visibleitemcount;    Private Boolean firstload = true; Public Photowalladapter (context context, int resource, string[] ObjectS, GridView Mphotowall) {Super (context, resource, objects);        Gets the maximum available memory for the application and allocates 1/8 of memory to memorycache long maxmemory = Runtime.getruntime (). MaxMemory ();        MemoryCache = new Mylrucache ((int) (MAXMEMORY/8));        tasks = new arraylist<> ();        This.mphotowall = Mphotowall;    Set the wall of the photo to listen for the scrolling event this.mPhotoWall.setOnScrollListener (this); } @Override public View getView (int position, view Convertview, ViewGroup parent) {String imageUrl = (string        ) GetItem (position);        View view = null;        if (Convertview = = null) {view = View.inflate (GetContext (), r.layout.griditem_photo_wall, NULL);        } else {view = Convertview;        } ImageView ImageView = (ImageView) View.findviewbyid (R.id.photo);        Imageview.settag (IMAGEURL);        Setimageview (Imageview,imageurl);    return view; } private void Setimageview (ImageView ImageView, String imageUrl) {Bitmap Bitmap = MemoryCache. Getbitmapfrommemorycache (IMAGEURL);        if (bitmap = = null) {Imageview.setimageresource (R.drawable.empty_photo);        }else{Imageview.setimagebitmap (bitmap); }} private void LoadBitmap (int firstvisibleitem, int visibleitemcount) {for (int i = Firstvisibleitem; I &l T Firstvisibleitem + visibleitemcount;            i++) {String imageUrl = images.imagethumburls[i];            ImageView ImageView = (ImageView) mphotowall.findviewwithtag (IMAGEURL);            Bitmap Bitmap = Memorycache.getbitmapfrommemorycache (IMAGEURL);                if (bitmap = = null) {//Open background Download task Downloadbitmaptask task = new Downloadbitmaptask ();                Tasks.add (Task);            Task.execute (IMAGEURL);            }else {imageview.setimagebitmap (bitmap); }}} @Override public void onscrollstatechanged (Abslistview view, int scrollstate) {log.i (TAG, "roll The state of the moving bar changes: "+ scrollstate);        if (scrollstate = = Scroll_state_idle) {//Load picture LoadBitmap (Firstvisibleitem, VisibleItemCount);        } else {cancletasks (); }} @Override public void onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcou        NT) {this.firstvisibleitem = Firstvisibleitem;        This.visibleitemcount = VisibleItemCount;            if (firstload && visibleitemcount > 0) {loadbitmap (firstvisibleitem,visibleitemcount);        Firstload = false;        } log.i (TAG, "Firstvisibleitem:" + Firstvisibleitem);    LOG.I (TAG, "VisibleItemCount:" + visibleitemcount);  }/** * */public void Cancletasks () {if (tasks! = null) {for (Downloadbitmaptask task:            Tasks) {Task.cancel (false); }}}/** * task to download pictures */Private class Downloadbitmaptask extends Asynctask<string,void,bitmap&gt ; {String ImageuRl        @Override protected Bitmap doinbackground (String ... params) {imageUrl = params[0];        Bitmap Bitmap = Downloadbitmap (IMAGEURL);        LOG.I (TAG, bitmap.tostring ());        if (bitmap! = null) {//bar download bitmap added to the in-memory cache Memorycache.addbitmaptomemorycache (IMAGEURL,BITMAP);    } return bitmap; } @Override protected void OnPostExecute (Bitmap Bitmap) {ImageView ImageView = (ImageView) mphot            Owall.findviewwithtag (IMAGEURL);            if (ImageView! = null && bitmap! = null) {Imageview.setimagebitmap (bitmap);        } tasks.remove (this);            } private Bitmap Downloadbitmap (String imageUrl) {HttpURLConnection conn = null;            Bitmap Bitmap = null;                try {URL url = new URL (imageUrl);                conn = (httpurlconnection) url.openconnection ();                Conn.setconnecttimeout (5 * 1000); Conn.setReadTimeout (5 * +);//Conn.connect ();                InputStream in = Conn.getinputstream ();            Bitmap = Bitmapfactory.decodestream (in);            } catch (Exception e) {e.printstacktrace ();                }finally {if (conn! = null) {conn.disconnect ();        }} return bitmap; }    }}

  

Implementation of Android Photo wall

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.