Android working with Volley Library

转:http://www.androidhive.info/2014/05/android-working-with-volley-library-1/


Android volley is a networking librarywas introduced to make networking calls much easier, faster without writingtons of code. By default all the volley network calls works asynchronously, sowe don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Someof them are

1. Request queuing and prioritization
2. Effective request cache and memory management
3. Extensibility and customization of the library to our needs
4. Cancelling the requests

DOWNLOAD CODE

Before getting into this tutorial, Isuggested you to view the below presentation by Ficus Kirkpatrick at Google I/O to get an overviewof volley.

 

1. Downloading & making volley.jar

We will start with installing toolsrequired to clone and build volley project. For this we need git (to clone theproject) and ant (to build) tools.

1.1 Installing Git
Git software is used to clone git projects into your local workspace. Download& install git, once installed run 
git command in terminal just to makesure that it is accessible via command line. If you are getting git command notfound error, add the git installation directory to environmental variables.

1.2 Installing apache ant
Apache ant is a command-line tool used to build the source code. Download ant fromhttps://ant.apache.org/bindownload.cgi and add the bin pathto environmental variables. You should able to execute 
ant command too in terminal.

1.3 Cloning volley library
Open command prompt, navigate to a location where you want to clone volley andexecute following command. This will download a copy of volley library intoyour local drive.

git clone https://android.googlesource.com/platform/frameworks/volley

1.4 Making volley.jar
You can use the volley as a library project to your main project or you cansimply generate volley.jar and paste it in project libs folder.To generate volley.jar, move into volley dir (cd volley) and executebelow commands.

android update project -p .

 

ant jar

You can find generated volley.jar involley bin folder.

The following video will show you theprocess of building volley project.

If you are unsuccessful in building thevolley, meanwhile you can download volley.jar here.

2. Adding volley.jar to your project

In Eclipse create a new project bynavigating to File New Android Application Project and fill required details. Oncethe project is created paste the volley.jar in libs folder.

 

3. Creating Volley Singleton class

The best way to maintain volley coreobjects and request queue is, making them global by creating a singleton classwhich extends Application object.In your project create a class nameAppController.java and extendthe class from Application and add the following code.

AppController.java

package info.androidhive.volleyexamples.app;

 

import info.androidhive.volleyexamples.volley.utils.LruBitmapCache;

import android.app.Application;

import android.text.TextUtils;

 

import com.android.volley.Request;

import com.android.volley.RequestQueue;

import com.android.volley.toolbox.ImageLoader;

import com.android.volley.toolbox.Volley;

 

public class AppController extends Application {

 

    public static final String TAG = AppController.class

            .getSimpleName();

 

    private RequestQueue mRequestQueue;

    private ImageLoader mImageLoader;

 

    private static AppController mInstance;

 

    @Override

    public void onCreate() {

        super.onCreate();

        mInstance = this;

    }

 

    public static synchronized AppController getInstance() {

        return mInstance;

    }

 

    public RequestQueue getRequestQueue() {

        if (mRequestQueue == null) {

            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        }

 

        return mRequestQueue;

    }

 

    public ImageLoader getImageLoader() {

        getRequestQueue();

        if (mImageLoader == null) {

            mImageLoader = new ImageLoader(this.mRequestQueue,

                    new LruBitmapCache());

        }

        return this.mImageLoader;

    }

 

    public <T> void addToRequestQueue(Request<T> req, String tag) {

        // set the default tag if tag is empty

        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        getRequestQueue().add(req);

    }

 

    public <T> void addToRequestQueue(Request<T> req) {

        req.setTag(TAG);

        getRequestQueue().add(req);

    }

 

    public void cancelPendingRequests(Object tag) {

        if (mRequestQueue != null) {

            mRequestQueue.cancelAll(tag);

        }

    }

}

Create another class named LruBitmapCache.java andpaste the below code. This class is required to handle image cache.

LruBitmapCache.java

package info.androidhive.volleyexamples.volley.utils;

 

import com.android.volley.toolbox.ImageLoader.ImageCache;

 

import android.graphics.Bitmap;

import android.support.v4.util.LruCache;

 

public class LruBitmapCache extends LruCache<String, Bitmap> implements

        ImageCache {

    public static int getDefaultLruCacheSize() {

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        final int cacheSize = maxMemory / 8;

 

        return cacheSize;

    }

 

    public LruBitmapCache() {

        this(getDefaultLruCacheSize());

    }

 

    public LruBitmapCache(int sizeInKiloBytes) {

        super(sizeInKiloBytes);

    }

 

    @Override

    protected int sizeOf(String key, Bitmap value) {

        return value.getRowBytes() * value.getHeight() / 1024;

    }

 

    @Override

    public Bitmap getBitmap(String url) {

        return get(url);

    }

 

    @Override

    public void putBitmap(String url, Bitmap bitmap) {

        put(url, bitmap);

    }

}

Open AndroidManifest.xml andadd this singleton class in <application> tag using android:namepropertyto execute this class automatically whenever app launches. Also add INTERNETpermission as we are going to makenetwork calls.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="info.androidhive.volleyexamples"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="19" />

 

    <uses-permission android:name="android.permission.INTERNET" />

 

    <application

        android:name="info.androidhive.volleyexamples.app.AppController"

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <!-- all activities and other stuff -->

    </application>

 

</manifest>

 

4. Making JSON request

Volley provides an easy to make jsonrequests. If you are expecting json object in the response, you should use JsonObjectRequest class or if the response is jsonarray, JsonArrayRequest class should be used.

4.1 Making json object request
Following code will make a json object request where the json response willstart with object notation ‘{

// Tag used to cancel the request

String tag_json_obj = "json_obj_req";

 

String url = "http://api.androidhive.info/volley/person_object.json";

         

ProgressDialog pDialog = new ProgressDialog(this);

pDialog.setMessage("Loading...");

pDialog.show();    

         

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,

                url, null,

                new Response.Listener<JSONObject>() {

 

                    @Override

                    public void onResponse(JSONObject response) {

                        Log.d(TAG, response.toString());

                        pDialog.hide();

                    }

                }, new Response.ErrorListener() {

 

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                        // hide the progress dialog

                        pDialog.hide();

                    }

                });

 

// Adding request to request queue

AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);



4.2 Making json array request
Following will make json array request where the json response starts witharray notation ‘[

// Tag used to cancel the request

String tag_json_arry = "json_array_req";

 

String url = "http://api.androidhive.info/volley/person_array.json";

         

ProgressDialog pDialog = new ProgressDialog(this);

pDialog.setMessage("Loading...");

pDialog.show();    

         

JsonArrayRequest req = new JsonArrayRequest(url,

                new Response.Listener<JSONArray>() {

                    @Override

                    public void onResponse(JSONArray response) {

                        Log.d(TAG, response.toString());       

                        pDialog.hide();            

                    }

                }, new Response.ErrorListener() {

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                        pDialog.hide();

                    }

                });

 

// Adding request to request queue

AppController.getInstance().addToRequestQueue(req, tag_json_arry);

 

5. Making String request

StringRequest class will be used to fetch anykind of string data. The response can be json, xml, html or plain text.

// Tag used to cancel the request

String  tag_string_req = "string_req";

 

String url = "http://api.androidhive.info/volley/string_response.html";

         

ProgressDialog pDialog = new ProgressDialog(this);

pDialog.setMessage("Loading...");

pDialog.show();    

         

StringRequest strReq = new StringRequest(Method.GET,

                url, new Response.Listener<String>() {

 

                    @Override

                    public void onResponse(String response) {

                        Log.d(TAG, response.toString());

                        pDialog.hide();

 

                    }

                }, new Response.ErrorListener() {

 

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                        pDialog.hide();

                    }

                });

 

// Adding request to request queue

AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

 

6. Adding post parameters

It is obvious that sometimes we need tosubmit request parameters while hitting the url. To do that we have to override getParams() methodwhich should return list of parameters to be send in a key value format.

If you observe below example, I amsubmitting nameemail and password asrequest parameters.

// Tag used to cancel the request

String tag_json_obj = "json_obj_req";

 

String url = "http://api.androidhive.info/volley/person_object.json";

         

ProgressDialog pDialog = new ProgressDialog(this);

pDialog.setMessage("Loading...");

pDialog.show();    

         

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,

                url, null,

                new Response.Listener<JSONObject>() {

 

                    @Override

                    public void onResponse(JSONObject response) {

                        Log.d(TAG, response.toString());

                        pDialog.hide();

                    }

                }, new Response.ErrorListener() {

 

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                        pDialog.hide();

                    }

                }) {

 

            @Override

            protected Map<String, String> getParams() {

                Map<String, String> params = new HashMap<String, String>();

                params.put("name", "Androidhive");

                params.put("email", "abc@androidhive.info");

                params.put("password", "password123");

 

                return params;

            }

 

        };

 

// Adding request to request queue

AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

7. Adding request headers

Just like adding request parameters, tosend request headers, we have to override getHeaders(). In belowexample I am sending Content-Type and apiKey inrequest headers.

// Tag used to cancel the request

String tag_json_obj = "json_obj_req";

 

String url = "http://api.androidhive.info/volley/person_object.json";

         

ProgressDialog pDialog = new ProgressDialog(this);

pDialog.setMessage("Loading...");

pDialog.show();    

         

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,

                url, null,

                new Response.Listener<JSONObject>() {

 

                    @Override

                    public void onResponse(JSONObject response) {

                        Log.d(TAG, response.toString());

                        pDialog.hide();

                    }

                }, new Response.ErrorListener() {

 

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                        pDialog.hide();

                    }

                }) {

 

            /**

             * Passing some request headers

             * */

            @Override

            public Map<String, String> getHeaders() throws AuthFailureError {

                HashMap<String, String> headers = new HashMap<String, String>();

                headers.put("Content-Type", "application/json");

                headers.put("apiKey", "xxxxxxxxxxxxxxx");

                return headers;

            }

 

        };

 

// Adding request to request queue

AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);

 

8. Making Image request

Volley introduced custom image viewelement called NetworkImageView to display the images from anURL. Previously downloading images and maintaining caches is a tough job. Nowusing volley this can be done with very few lines of code.

8.1 Loading image in NetworkImageView
Following will load an image from an URL into NetworkImageView.

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

 

// If you are using NetworkImageView

imgNetWorkView.setImageUrl(Const.URL_IMAGE, imageLoader);



8.2 Loading image in ImageView
If you want to load image into ImageView instead of NetworkImageView, you cando that too as mentioned below. Here we will have success and error callbacks,you have to take appropriate action depending on the need. Below in onResponse() methodusing response.getBitmap() I am loading bitmap into anImageView.

ImageLoader imageLoader = AppController.getInstance().getImageLoader();

 

// If you are using normal ImageView

imageLoader.get(Const.URL_IMAGE, new ImageListener() {

 

    @Override

    public void onErrorResponse(VolleyError error) {

        Log.e(TAG, "Image Load Error: " + error.getMessage());

    }

 

    @Override

    public void onResponse(ImageContainer response, boolean arg1) {

        if (response.getBitmap() != null) {

            // load image into imageview

            imageView.setImageBitmap(response.getBitmap());

        }

    }

});



8.3 Defining placeholder image and error image
Here is another way of displaying image into ImageView with the option ofplaceholder for loader and error. The loader placeholder will be displayeduntil the image gets downloaded. If the image fails to download, the errorplaceholder will be displayed.

// Loading image with placeholder and error image

imageLoader.get(Const.URL_IMAGE, ImageLoader.getImageListener(

                imageView, R.drawable.ico_loading, R.drawable.ico_error));

 

9. Handling the volley Cache

Volley comes with powerful cachemechanism to maintain request cache. This saves lot of internet bandwidth andreduces user waiting time. Following are few example of using volley cachemethods.

9.1 Loading request from cache
Like below you can check for a cached response of an URL before making anetwork call.

Cache cache = AppController.getInstance().getRequestQueue().getCache();

Entry entry = cache.get(url);

if(entry != null){

    try {

        String data = new String(entry.data, "UTF-8");

        // handle data, like converting it to xml, json, bitmap etc.,

    } catch (UnsupportedEncodingException e) {     

        e.printStackTrace();

        }

    }

}else{

    // Cached response doesn't exists. Make network call here

}



9.2 Invalidate cache
Invalidate means we are invalidating the cached data instead of deleting it.Volley will still uses the cached object until the new data received fromserver. Once it receives the response from the server it will override theolder cached response.

AppController.getInstance().getRequestQueue().getCache().invalidate(url, true);



9.3 Turning off cache
If you want disable the cache for a particular url, you can use setShouldCache() methodas below.

// String request

StringRequest stringReq = new StringRequest(....);

 

// disable cache

stringReq.setShouldCache(false);



9.4 Deleting cache for particular URL
Use remove() to delete cache of an URL.

AppController.getInstance().getRequestQueue().getCache().remove(url);



9.5 Deleting all the cache
Followoing will delete the cache for all the URLs.

AppController.getInstance().getRequestQueue().getCache().clear(url);

 

10. Cancelling requests

If you notice addToRequestQueue(request,tag) method, it accepts two parameters. One is request object and other isrequest tag. This tag will be used to identify the request while cancelling it.If the tag is same for multiple requests, all the requests will be cancelled. cancellAll() methodis used to cancel any request.


10.1 Cancel single request
Following will cancel all the request with the tag named “feed_request”

String tag_json_arry = "json_req";

ApplicationController.getInstance().getRequestQueue().cancelAll("feed_request");

10.2 Cancel all requests
If you don’t pass any tag to cancelAll() method, it will cancel the request inrequest queue.

ApplicationController.getInstance().getRequestQueue().cancelAll();

 

11. Request prioritization

If you are making multiple request atthe same time, you can prioritize the requests those you want be executedfirst. The priory can be NormalLowImmediate and High.

private Priority priority = Priority.HIGH;

 

StringRequest strReq = new StringRequest(Method.GET,

                Const.URL_STRING_REQ, new Response.Listener<String>() {

 

                    @Override

                    public void onResponse(String response) {

                        Log.d(TAG, response.toString());

                        msgResponse.setText(response.toString());

                        hideProgressDialog();

 

                    }

                }, new Response.ErrorListener() {

 

                    @Override

                    public void onErrorResponse(VolleyError error) {

                        VolleyLog.d(TAG, "Error: " + error.getMessage());

                        hideProgressDialog();

                    }

                }) {

            @Override

            public Priority getPriority() {

                return priority;

            }

 

        };

 

Missing! Making XML request

As of now volley doesn’t provided anynative classes to make XML requests, but this can be achieved by building acustom xml wrapper class by utilizing volley’s customization capabilities. Thepart of writing xml parser using volley will be covered in upcoming tutorial.

I have given a sample project coveringthe scenarios explained in this tutorial. Download it andlet’s discuss the queries if you have any in the comments section 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值