Use of Android Volley framework (iii)

Source: Internet
Author: User

Image Request

To make it easier to use picture requests in volley, we also first encapsulate a Volleycontroller class with aImageLoader

 PackageCom.javen.volley;ImportAndroid.content.Context;Importandroid.text.TextUtils;Importcom.android.volley.Request;ImportCom.android.volley.RequestQueue;ImportCom.android.volley.toolbox.ImageLoader;ImportCom.android.volley.toolbox.Volley; Public classVolleycontroller {//create a tag to facilitate debugging or log    Private Static FinalString TAG = "Volleycontroller"; //to create a global request queue    PrivateRequestqueue Reqqueue; PrivateImageloader Imageloader; //creates a static Applicationcontroller object that is easy to access globally    Private StaticVolleycontroller minstance; PrivateContext Mcontext; PrivateVolleycontroller (Context context) {Mcontext=context; }    /*** Below are the methods for adding request cancellation requests that require our own encapsulation*/    //used to return a Volleycontroller single case     Public StaticVolleycontroller getinstance (context context) {if(Minstance = =NULL) {            synchronized(Volleycontroller.class)            {                if(Minstance = =NULL) {minstance=NewVolleycontroller (context); }            }        }        returnminstance; }    //used to return a global Requestqueue object and create it if it is empty     Publicrequestqueue Getrequestqueue () {if(Reqqueue = =NULL){            synchronized(Volleycontroller.class)            {                if(Reqqueue = =NULL) {Reqqueue=Volley.newrequestqueue (Mcontext); }            }        }        returnReqqueue; }             PublicImageloader Getimageloader () {getrequestqueue (); //if Imageloader is empty, it is created, and the second parameter represents the class that handles the image cache        if(imageloader==NULL) {Imageloader=NewImageloader (Reqqueue,NewLrubitmapcache ()); }        returnImageloader; }    /*** Add Request object to Requestqueue, because request has *stringrequest,jsonobjectresquest ... * etc., you need to use the * generic type. *tag can also be used as an optional parameter in order to mark each of the different requests*/     Public<T>voidAddtorequestqueue (request<t>req, String tag) {        //if the tag is empty, the default tag is used .Req.settag (Textutils.isempty (tag)?Tag:tag);    Getrequestqueue (). Add (req); }     Public<T>voidAddtorequestqueue (request<t>req)        {Req.settag (TAG);    Getrequestqueue (). Add (req); }    //Cancel requests through the Tag property of each Request object     Public voidcancelpendingrequests (Object tag) {if(Reqqueue! =NULL) {Reqqueue.cancelall (tag); }    }}
  1. After completing the above steps, we first need to get the Imageloader object when using
    Imageloader imageloader=volleycontroller.getinstance (context). Getimageloader ();
  2. Loading a picture into ImageView can use an image view provided by volley itself,NetworkImageView, a few lines of code can be done.
    // to layout networkimageview in a layout file Networkimageview imageview=// need to use Imageloader imageview.setimageurl (Url,imageloader);

    If you want to load the picture directly into the ImageView, you can do this by using the following methods:

    Imageloader imageloader=volleycontroller.getinstance (context). Getimageloader (); Imageloader.get (URL,NewImagelistener () {@Override Public voidOnresponse (Imagecontainer response,BooleanArg) {                if(Response.getbitmap ()! =NULL){                //Set ImageView//Imageview.setimagebitmap (Response.getbitmap ());}} @Override Public voidonerrorresponse (volleyerror error) {L.E ("Image Error" +error.getmessage ()); }            });



Volley Cache

Volley has a powerful caching mechanism to maintain the requested cache, which saves unnecessary network consumption and wait time, and here are some common methods for caching

  1. read requests from the cache: First read from the cache to see if there is any cached data, and if not, request network data
    Cache cache=volleycontroller.getinstance (context). Getrequestqueue (). GetCache (); Entry Entry=cache.get (URL); if(entry!=NULL){            Try{String Data=NewString (Entry.data, "Utf-8"); //process data, convert it to Json,xml,bitmap, etc.}Catch(Exception e) {e.printstacktrace (); }        }Else{            //does not exist in the cache, do network requests}
  2. Cache invalidation : Cache invalidation does not mean that the cache is deleted, volley will still use the cached object until the server returns new data, and once the new data is received, it will overwrite the original cache
    Volleycontroller.getinstance (context). Getrequestqueue (). GetCache (). Invalidate (URL,true);

  3. Turn off caching : If you want to disable caching for a specific URL, you can use the following methods
    Volleycontroller.getinstance (context). Getrequestqueue (). GetCache (). Remove (URL);
  4. Delete a cache from a specific URL
    Volleycontroller.getinstance (context). Getrequestqueue (). GetCache (). Remove (URL);

  5. Delete all Caches
    Volleycontroller.getinstance (context). Getrequestqueue (). GetCache () clear (URL);
    Summarize:

    In summary, has learned the use of volley framework, in practical applications encountered specific problems need to be specific considerations, when necessary to learn to consult the information, in addition to the above mentioned references, it is best to FQ to see Google's official documents about volley.

    Reference: Android working with volley Library Blog

Use of Android Volley framework (iii)

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.