Android batch image loading classic series-a multi-layout News list using the Volley framework,

Source: Internet
Author: User

Android batch image loading classic series-a multi-layout News list using the Volley framework,

I. Problem Description

Volley is a network communication library released by Google in 2013 to implement the Android platform. It mainly provides network communication and image download solutions. For example, the steps for downloading images from the Internet may be as follows:

Start reading the image in getView () of ListAdapter.

Through AsyncTask and other mechanisms, HttpURLConnection is used to set the attributes of the corresponding ImageView in onPostExecute () of AsyncTask. In Volley, only ImageLoader is required.

  Case study --View current image news:

Ii. Main Components of the case

1. The RequestQueue Request queue puts the StringRequest request into the queue for asynchronous processing. The main code is as follows:

// Create a RequestQueue and send an asynchronous request RequestQueue mRequestQueue = Volley. newRequestQueue (this); // StringRequest request = new StringRequest (...); // Create a client request mRequestQueue. add (request); // add the request to the queue and asynchronously execute the request

2. ImageLoader caches and asynchronously loads network images

// Create an ImageLoader to save the image to the cache and retrieve the image from the cache. // The first parameter is the previously created RequestQueue object. // The second parameter is the image cache setting, for details, see BitmapCache code ImageLoader mImageLoader = new ImageLoader (mRequestQueue, new BitmapCache (); // load the image, first load the image from the memory, and then load the memory from the network. // url: image network path // view the image ImageView control, R. drawable. default: the default image is not loaded. drawable. error: The image mImageLoader that fails to be loaded. get (url, ImageLoader. getImageListener (view, R. drawable. default, R. drawable. error ));
Iii. Complete case code

Note: The server environment must be self-built

1. BitmapCache and SunNewsApplication components:

  (1) BitmapCache:

Public class BitmapCache implements ImageCache {private LruCache <String, Bitmap> mCache; public BitmapCache () {// gets the maximum available memory, when the memory usage exceeds this value, it will cause an OutOfMemory exception // use 1/8 of the maximum available memory value as the cache size. Int maxsize = (int) (Runtime. getRuntime (). maxMemory ()/1024)/8; mCache = new LruCache <String, Bitmap> (maxsize) {// rewrite this method to measure the size of each image, default number of returned images @ Override protected int sizeOf (String key, Bitmap value) {return super. sizeOf (key, value) ;}};}/*** get the cached image */@ Override public Bitmap getBitmap (String key) {return mCache. get (key);}/*** save to cache */@ Override public void putBitmap (String key, Bitmap bitmap) {I F (bitmap! = Null) mCache. put (key, bitmap );}}

(2) SunNewsApplication:

Public class SunNewsApplication extends Application {private ImageLoader mImageLoader; private RequestQueue mRequestQueue; public void onCreate () {// create RequestQueue, which can send asynchronous requests to mRequestQueue = Volley. newRequestQueue (this); // create an ImageLoader to save the image to the cache and retrieve it from the cache. mImageLoader = new ImageLoader (mRequestQueue, new BitmapCache ();} public ImageLoader getmImageLoader () {return mImageLoader;} public RequestQueue getmRequestQueue () {return mRequestQueue ;}}

2. MoreStyleNewsListViewAdapter code:

Public class MoreStyleNewsListViewAdapter extends BaseAdapter {private Activity mActivity; private List <NewsItem> newsList; private ImageLoader imageLoader; public MoreStyleNewsListViewAdapter (Activity mActivity, List <NewsItem> newsList) {this. mActivity = mActivity; this. newsList = newsList; imageLoader = (SunNewsApplication) mActivity. getApplication ()). getmImageLoader ();} private final int TYPE_COUNT = 2 ;/*** Return the display type data of the data item */@ Override public int getItemViewType (int position) {return newsList! = Null? NewsList. get (position ). getStyle ():-1;}/*** number of returned types */@ Override public int getViewTypeCount () {return TYPE_COUNT;} @ Override public int getCount () {return newsList. size () ;}@ Override public Object getItem (int position) {return newsList. get (position) ;}@ Override public long getItemId (int position) {return position ;}@ Override public View getView (int position, View convertView, ViewGroup parent) {ViewHolder holder = null; NewsItem item = newsList. get (position); if (convertView = null) {holder = new ViewHolder (); // set layout. xml Conversion to View switch (item. getStyle () {case 0: convertView = LayoutInflater. from (mActivity ). inflate (R. layout. news_item1, null); holder. ivImg1 = (ImageView) convertView. findViewById (R. id. ivNewsImg); break; case 1: convertView = LayoutInflater. from (mActivity ). inflate (R. layout. news_item2, null); holder. ivImg1 = (ImageView) convertView. findViewById (R. id. ivImg1); holder. ivimg 2 = (ImageView) convertView. findViewById (R. id. ivimg); holder. ivImg3 = (ImageView) convertView. findViewById (R. id. ivImg3); break;} holder. tvTilte = (TextView) convertView. findViewById (R. id. tvTitle); convertView. setTag (holder); // Record ID} else {holder = (ViewHolder) convertView. getTag ();} // bind the data holder to the ui element. tvTilte. setText (item. getTitle (); // load the image, first load it from the memory, and then the memory does not load imageLoader from the network. get (item. getImgUrl () [0], ImageLoader. getImageListener (holder. ivImg1, R. drawable. default_big, R. drawable. default_big); switch (item. getStyle () {case 1: imageLoader. get (item. getImgUrl () [1], ImageLoader. getImageListener (holder. ivimg 2, R. drawable. default_big, R. drawable. default_big); imageLoader. get (item. getImgUrl () [2], ImageLoader. getImageListener (holder. ivImg3, R. drawable. default_big, R. drawable. default_big); break;} Log. d ("jereh", "getView ()"); return convertView;} private class ViewHolder {private TextView tvTilte; private ImageView ivImg1; private ImageView ivimg; private ImageView ivImg3 ;}}

3. MainActivity code

Public class MainActivity extends Activity {private RadioGroup rgChannel; private List <NewsItem> newsList = new ArrayList <NewsItem> (); private MoreStyleNewsListViewAdapter adapter; private ListView newsListView; private RequestQueue queue; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_home); queue = (SunNewsApplicat Ion) super. getApplication ()). getmRequestQueue (); initView (); requestData ();} private void initView () {rgChannel = (RadioGroup) super. findViewById (R. id. rgChannel); rgChannel. check (R. id. rbToday); newsListView = (ListView) super. findViewById (R. id. lvNews); adapter = new MoreStyleNewsListViewAdapter (this, newsList); newsListView. setAdapter (adapter);}/*** asynchronous request to obtain Network Data */private void requestData () {String url =" Http: // 192.168.0.107: 8080/21-sun/NewsListServlet "; StringRequest request = new StringRequest (Method. GET, url, new Response. listener <String> () {@ Override public void onResponse (String ret) {// The request is successfully called and the returned result is Gson gson = new Gson (); List list = gson. fromJson (ret, new TypeToken <ArrayList <NewsItem> (){}. getType (); newsList. addAll (list); adapter. notifyDataSetChanged () ;}}, new Response. errorListener () {@ Overr Ide public void onErrorResponse (VolleyError error) {// call Log. d ("jereh", "network loading failed! ") ;}}); Queue. add (request); // add the request to the queue and asynchronously execute the request }}

4. NewsItem entity class

Public class NewsItem {private String title; // news title private int style; // 0: normal 1: Multiple figures 2: private String [] imgUrl; // news image... // Omit setter/getter}

5. NewsListServlet code on the server

Public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/json; charset = UTF-8"); List <NewsItem> newsList = new ArrayList <NewsItem> (); NewsItem item1 = new NewsItem (); item1.setTitle ("the only maintenance construction enterprise that has obtained the highest credit grade in Xinjiang"); item1.setStyle (0); item1.setImgUrl (new String [] {"http://news.21-sun.com/UserFiles/x_Image/x_20150624164627_0.j Pg "}); newsList. add (item1 );... NewsItem item4 = new NewsItem (); item4.setTitle ("de engineering 2015 road mechanical quality miles into Henan"); item4.setStyle (1); item4.setImgUrl (newString [] {"http://news.21-sun.com/UserFiles/x_Image/x_20150624101251_0.jpg ", "http://news.21-sun.com/UserFiles/x_Image/x_20150624080852_0.jpg", "http://news.21-sun.com/UserFiles/x_Image/x_20150623141354_0.jpg"}); newsList. add (item4); NewsItem item5 = new NewsItem (); item5.setTitle ("Wang guiqing, general manager of Dezhou Bao Ding: She loves learning"); item5.setStyle (0 ); item5.setImgUrl (new String [] {"http://news.21-sun.com/UserFiles/x_Image/x_20150624123300_0.jpg"}); newsList. add (item5); JSONArray jsonArr = JSONArray. fromObject (newsList); System. out. println (jsonArr); response. getWriter (). print (jsonArr. toString ());}

 

For more information, clickView Source CodeRun the test in person.

For questions or technical exchanges, please join the official QQ group: (452379712)

 

Author: Jerry Education
Source: http://www.cnblogs.com/jerehedu/
The copyright of this article belongs to Yantai Jerry Education Technology Co., Ltd. and the blog Park. You are welcome to repost it. However, you must keep this statement without the author's consent and provide the original article connection on the article page, otherwise, you are entitled to pursue legal liability.

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.