Simple implementation of asynchronous delayed loading and SD card caching for ListView network images

Source: Internet
Author: User

Imported to the database? Will SimpleAdapter be used? Congratulations! After reading this article, you will find that the asynchronous delayed loading of ListView network images and caching SDcard ...... So easy!

I believe that when I first came into contact with ListView and needed to implement the network image loading function, I started from starting a new thread to asynchronously downloading network images, and finally realized the delayed loading of images and caching SDcard, it will be plagued by various problems. I remember that it took two days to fully implement all the functional requirements. Even if I learned to use the open-source framework ImageLoader, it took a while to configure and use it! Because of this series of problems, I think about how to encapsulate the steps that most developers do not need to take or are complex for better use. The following method is used:

1) First, we need an open-source framework ImageLoader. Official Website: https://github.com/dodola/android-universal-image-loader. click the download ZIP button on the right of the page to download the compressed package and decompress it, import the library to your project. If you do not want to download the library from the official website, you can directly upload the library with my attachment)

2) download the attachment, copy the ImageSimpleAdapter. java and AbsListViewBaseActivity. java in the attachment to your project. After the copy is complete, ImageSimpleAdapter. java will report an error and find the error line because the resource cannot be found during DisplayImageOptions options initialization: XXXX cannot be resolved or is not a field)


DisplayImageOptions options = new DisplayImageOptions.Builder()        .showStubImage(R.drawable.ic_stub).showImageForEmptyUri(R.drawable.ic_empty).showImageOnFail(R.drawable.ic_error).cacheInMemory().cacheOnDisc()        .displayer(new RoundedBitmapDisplayer(5)).build();

Decompress displayimageoptionsimage .rar In the compressed package, copy the three images to the res/drawable folder, or replace them with the one you want.

The relationship between the three images is as follows:

R. drawable. ic_stub // The default image starting from loading. It will be displayed during scrolling.

R. drawable. ic_empty // The image is displayed when it is null.

R. drawable. ic_error // This image is displayed when an error occurs during image loading.

   .displayer(new RoundedBitmapDisplayer(5))//RoundedBitmapDisplayer(5).Sets the rounded corner of the image. 0 indicates no rounded corner effect.

Note: To use the open-source framework ImageLoader, because it involves internet access and image caching, you need to get the permission: "android. permission. INTERNET and android. permission. WRITE_EXTERNAL_STORAGE.

3) at this point, all preparations have been completed. The next step is your own code. The code is very simple. inherit the Activity where your ListView is located from AbsListViewBaseActivity, and then find your own ListView to set the ImageSimpleAdapter adapter. The method for configuring ImageSimpleAdapter in ListVIew is the same as that for configuring SimpleAdapter! Just because network download is involved, in order to ensure program stability, a new thread is required. Refer to the code below:


Import java. util. arrayList; import java. util. hashMap; import java. util. list; import org. json. JSONArray; import org. json. JSONException; import org. json. JSONObject; import android. OS. bundle; import android. widget. listView; public class MainActivity extends AbsListViewBaseActivity {int [] mTo = new int [] {R. id. imageView1, R. id. textView1}; String [] mFrom = new String [] {"image", "text"}; List <HashMap <String, Obje Ct> mAllData = new ArrayList <HashMap <String, Object> (); @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) findViewById (R. id. listView1); new Thread () {public void run () {// a simulated simple server is built using hfs because I am a test. HttpDownload. urlDownload (String httpFilePath) is self-written. It is used to obtain the content String of the json file through an input json file. String jsonStr = HttpDownload. urlDownload (" http://10.0.2.2:8080/http_server/tongzhi.txt "); Try {// JSONArray jsonArray = new JSONArray (jsonStr); for (int I = 0; I <jsonArray. length (); I ++) {JSONObject jsonObj = jsonArray. getJSONObject (I); // image is the image address of each parsed image line. String image = jsonObj. getString ("image"); String replyer = jsonObj. getString ("replyer"); HashMap <String, Object> map = new HashMap <String, Object> (); map. put ("image", image); map. put ("replyer", replyer); // construct mAllData of List <HashMap <String, Object> mAllData Based on the parsed data. add (map);} runOnUiThread (new Runnable () {public void run () {// R. layout. item_list is the row layout of ListView. It is very simple. It is a ImageView and a TextView, so the layout file will not be pasted (ListView) listView ). setAdapter (new ImageSimpleAdapter (MainActivity. this, mTo, mFrom, mAllData, R. layout. item_list) ;}}) ;}catch (JSONException e) {e. printStackTrace ();}};}. start ();}}


Line 33 of the above Code is useful to a small module written by myself. The function is to get the content string of the json file through an input json file, and the source code is as follows:


import java.io.IOException;import java.io.InputStream;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;import org.apache.http.util.ByteArrayBuffer;public class HttpDownload{    private HttpDownload(){};                                                                                                                                                                                                                                                                                                                                                                                                             public static String urlDownload(String httpFilePath)    {        String result;        InputStream is = null;        try        {            ByteArrayBuffer arrayBuffer = new ByteArrayBuffer(2000);            URL url = new URL(httpFilePath);            URLConnection connection = url.openConnection();            is  = connection.getInputStream();            int length = 0;            byte[] buffer = new byte[1024];            while(-1 != (length  = is.read(buffer)))            {                arrayBuffer.append(buffer, 0, length);            }            result =  new String(arrayBuffer.toByteArray(), 0, arrayBuffer.length()).toString();            return result;        }        catch (MalformedURLException e)        {            e.printStackTrace();        }        catch (IOException e)        {            e.printStackTrace();        }        finally        {            if (is != null)            {                try                {                    is.close();                }                catch (IOException e)                {                    e.printStackTrace();                }            }        }        return null;    }}


4) Now, all the steps are completed. The key code I personally modified and encapsulated is in the ImageSimpleAdapter in the attachment. If you are interested, you can view the implementation methods by yourself. There are detailed comments, which may be unclear or have better comments, you can leave a message to discuss or contact me (* ^__ ^ *)~. Email: 272548772@qq.com

In fact, some parts written by myself such as ImageSimpleAdapter can be put in the library uploaded by the attachment, so that many of the first two steps can be saved. However, if you want to customize the delayed loading status, it is inconvenient to display images with rounded corners. If you are interested, try it)

This article is from "Zhang Xueqing's blog" blog, please be sure to keep this source http://xueqing.blog.51cto.com/7895245/1294050

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.