Android's volley framework is used in the actual development process

Source: Internet
Author: User

In this chapter we talk about how to use it correctly in the actual development of volley. Nonsense not to say, to get to the chase.

Integrated volley

If you are developing a reader using Android studio, you can add remote dependencies directly:
  

    ‘com.mcxiaoke.volley:library:1.0.19‘

If the reader developed using ecplise can add jars to lib, they can be packaged into jars by their own source, and I will give the Volley.jar resources directly here. Click here to download Volley.jar

Volley's Requst
FinalTextView Mtextview = (TextView) Findviewbyid (R.id.text);//Instantiate the Requestqueue.Requestqueue queue = Volley.newrequestqueue ( This); String URL ="https://www.baidu.com/"; Stringrequest stringrequest =NewStringrequest (Request.Method.GET, URL,NewResponse.listener<string> () {@Override     Public void Onresponse(String response) {Mtextview.settext ("Response is:"+ response.substring (0, -)); }},NewResponse.errorlistener () {@Override     Public void Onerrorresponse(Volleyerror error) {Mtextview.settext ("that didn ' t work!"); }}); Queue.add (stringrequest);

This is the general use of volley:

    1. Create a Requestqueue object
    2. Create a subclass request object that inherits from the request abstract class
    3. Adding the Request object to the Requestqueue

      We passed four parameters in Stringrequest: Request method, URL string, callback for successful request, and callback for failed request. We can implement the specific logic we want in the callback. This is the case with stringrequest or jsonrequest and other objects that inherit the request class.
      In the development process, for example, in an activity there are multiple need to load the network image of the ImageView, we add multiple request to Requestqueue, the picture is not all displayed, we point back key. At this point, the acitivity is destroyed, and the request is still in the queue, and the view has been destroyed, which can easily affect the efficiency. So we can write the following code in the activity:
        

publicstaticfinal String TAG = MainActivity.class// Assume this exists.RequestQueue mRequestQueue;  // Assume this exists.// Set the tag on the request.stringRequest.setTag(TAG);// Add the request to the RequestQueue.mRequestQueue.add(stringRequest);

Here we set a label for each request, and the label is best defined as a class name, which is easy to manage. Then we can write this in the Stop method of the activity:

@OverrideprotectedvoidonStop () {    super.onStop();    ifnull) {        mRequestQueue.cancelAll(TAG);    }}

As you can see, we canceled all the request with this tag in Requestqueue.

Volley's Requestqueue:
在开发中,我们最好设计一个全局的RequestQueue对象,此时,你可能很容易想到在继承于Application中的Oncreate方法初始化它,但是这样子是不推荐的,会引起很多不必要的麻烦。现在我们通过单例模式来创建它:
 Public  class Mysingleton {    Private StaticMysingleton minstance;PrivateRequestqueue Mrequestqueue;PrivateImageloader Mimageloader;Private StaticContext Mctx;Private Mysingleton(Context context)        {mctx = context;        Mrequestqueue = Getrequestqueue (); Mimageloader =NewImageloader (Mrequestqueue,NewImageloader.imagecache () {Private Finallrucache<string, bitmap> cache =NewLrucache<string, Bitmap> ( -);@Override             PublicBitmapGetbitmap(String URL) {returnCache.get (URL); }@Override             Public void Putbitmap(String URL, Bitmap Bitmap)            {cache.put (URL, bitmap);    }        }); } Public Static synchronizedMysingletongetinstance(Context context) {if(Minstance = =NULL) {minstance =NewMysingleton (context); }returnMinstance; } PublicRequestqueueGetrequestqueue() {if(Mrequestqueue = =NULL) {Mrequestqueue = Volley.newrequestqueue (Mctx.getapplicationcontext ()); }returnMrequestqueue; } Public<T>void Addtorequestqueue(request<t> req)    {Getrequestqueue (). Add (req); } PublicImageloaderGetimageloader() {returnMimageloader; }}

Here we Volley.newRequestQueue(mCtx.getApplicationContext()); pass in the ApplicationContext object, which is a global object that causes a memory leak if we pass in the context of the activity or service. The Requestqueue object and a imageloader are initialized here. About Imageloader we'll go on, and now we can use requestqueue like this:

RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).    getRequestQueue();MySingleton.getInstance(this).addToRequestQueue(stringRequest);

This way, the Requestqueue is managed globally.

Volley's Networkimageview

Volley encapsulates a networkimageview that inherits from ImageView, remember that we also initialized a imageloader in the Requestqueue Singleton, which can be used in conjunction with Networkimageview in a simple and quick way. We can use Networkimageview in the ListView item layout and then load the picture with Imageloader.
The definition in the XML layout is simple:

<com.android.volley.toolbox.NetworkImageView        android:id="@+id/networkImageView"        android:layout_width="150dp"        android:layout_height="170dp"        android:layout_centerHorizontal="true" />

The code can then write in the view:

ImageLoader mImageLoader;NetworkImageView mNetworkImageView;privatestaticfinal"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);mImageLoader = MySingleton.getInstance(this).getImageLoader();mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

You can see that we have mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader); just passed in a URL and a loader on the method here.
Let's compare the code for ImageView with Imageloader:
  

Imageloader Mimageloader;ImageView Mimageview;private static final String Image_url ="Https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png";Mimageview = (ImageView) Findviewbyid (R. ID. Regularimageview);Mimageloader = Mysingleton. getinstance(this). Getimageloader();Mimageloader. Get(Image_url, Imageloader. Getimagelistener(Mimageview, R. drawable. def_image, R. drawable. Err_image));

Obviously, the code is not as concise as Networkimageview with Imageloader.

Android's volley framework is used in the actual development process

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.