3 steps to show network images with listview

Source: Internet
Author: User

1. retrieve images from the network

 

/*** Get the network image ** @ Param path the network image path * @ return * @ throws exception */public static byte [] getimage (string path) throws exception {URL url = new URL (PATH); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5*1000); Conn. setrequestmethod ("get"); inputstream instream = Conn. getinputstream (); If (Conn. getresponsecode () == 200) {return streamtool. readstream (instream);} return NULL ;}

 

2. Read data in the stream

/*** Read data in the stream * @ Param instream * @ return * @ throws exception */public static byte [] readstream (inputstream instream) throws exception {bytearrayoutputstream outstream = new bytearrayoutputstream (); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = instream. read (buffer ))! =-1) {outstream. Write (buffer, 0, Len);} outstream. Close (); instream. Close (); Return outstream. tobytearray ();}

 

3. Display in listview

 

Public class mainactivity extends activity {private edittext pathtext; private imageview; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); pathtext = (edittext) This. findviewbyid (R. id. path); imageview = (imageview) This. findviewbyid (R. id. imageview); button = (button) This. findviewbyid (R. id. button); butto N. setonclicklistener (new view. onclicklistener () {public void onclick (view v) {string Path = pathtext. gettext (). tostring (); try {byte [] DATA = imageservice. getimage (PATH); If (Data! = NULL) {Bitmap bitmap = bitmapfactory. decodebytearray (data, 0, Data. length); // construct a bitmap imageview. setimagebitmap (Bitmap); // complete the image display} else {toast. maketext (mainactivity. this, R. string. imageerror, 1 ). show () ;}} catch (exception e) {toast. maketext (mainactivity. this, R. string. neterror, 1 ). show (); E. printstacktrace ();}}});}}

 

Success!

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.