Transmitting network data using volley(14 09-16)
-
Upload
sokngim-sa -
Category
Education
-
view
51 -
download
0
Transcript of Transmitting network data using volley(14 09-16)
Transmitting Network Data Using Volley14/September/2016 – 20/September/2016 Prepared by: Ms. Sokngim Sa
Content
1. Introduction Volley2. Benefit of Volley3. Sending a Simple Request4. Setting Up a RequestQueue5. Using ImageLoader6. Using Request JSON7. Implementing a Custom Request
Using RequestString
1. Introduction VolleyVolley is an HTTP library that makes networking
for Android apps easier and most importantly, faster.
Using Volley in your Project: dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:24.0.0' compile 'com.android.volley:volley:1.0.0'}
2. Benefit of Volley Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with
standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request,
or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate
your UI with data fetched asynchronously from the network.
Debugging and tracing tools.
3. Sending a Simple Request Add the Internet permission Use newRequestQueue Send a RequestQueue Cancel a Request
2.1 Add the Internet Permission Add android.permission.INTERNET permission to
app's manifest
<uses-permission android:name="android.permission.INTERNET/>
2.2 Use newRequestQueue Volley provides a convenience method
Volley.newRequestQueue that sets up a RequestQueue for you, using default values, and starts the queue.
// Instantiate the RequestQueue.RequestQueue queue = Volley.newRequestQueue(this);
2.3 Send a Request
To send a request, you simply construct one and add it to the RequestQueue object with add(StringRequest Object).
// Add the request to the RequestQueue.queue.add(stringRequest);
Processing Send a Request
Example of RequestQueue and Send Request
2.4 Cancel a Request
To cancel a request, call cancelAll()on your Request object.
We can call cancel a request in onStop() method of An activtiy
mRequestQueue.cancelAll(Object Tag);
@Overrideprotected void onStop () { super.onStop(); if (mRequestQueue != null) { mRequestQueue.cancelAll(TAG); }}
Example
Define your tag and add it to your requests.
Example (Con)
In your activity's onStop() method, cancel all requests that have this tag.
3. Setting up a RequestQueue Set Up a Network and Cache Use a Singleton Pattern
3.1 Set Up a Network and Cache A RequestQueue needs two things to do its job: a
network to perform transport of the requests, and a cache to handle caching.
There are standard implementations of these available in the Volley toolbox: DiskBasedCache provides a one-file-per-response
cache with an in-memory index BasicNetwork provides a network transport based on
your preferred HTTP client. BasicNetwork is Volley's default network
implementation. A BasicNetwork must be initialized with the HTTP client your app is using to connect to the network. Typically this is an HttpURLConnection.
Example
Note
If you just need to make a one-time request and don't want to leave the thread pool around, you can create the RequestQueue wherever you need it and call stop() on the RequestQueue once your response or error has come back.
using the Volley.newRequestQueue() method described in Sending a Simple Request.
But the more common use case is to create the RequestQueue as a singleton to keep it running for the lifetime of your app.
3.2 Use a Singleton Pattern
If your application makes constant use of the network, it's probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality.
Another approach is to subclass Application and set up the RequestQueue in Application.onCreate(). A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
Create Singleton Class
In MainActivity
4. Making a Standard Request Introduction to Standard Request Request an Image Use ImageRequest Use ImageLoader and NetworkImageView Request JSON
4.1 Introduction to Standard Request StringRequest: Specify a URL and receive a raw
string in response. ImageRequest: Specify a URL and receive an
image in response. JsonObjectRequest and JsonArrayRequest
(both subclasses of JsonRequest): Specify a URL and get a JSON object or array (respectively) in response.
4.2 Request an Image
Volley offers the following classes for requesting images. These classes layer on top of each other to offer different levels of support for processing images: ImageRequest—a canned request for getting an
image at a given URL and calling back with a decoded bitmap. It also provides convenience features like specifying a size to resize to.
ImageLoader—a helper class that handles loading and caching images from remote URLs. ImageLoader is a an orchestrator for large numbers of ImageRequests, for example when putting multiple thumbnails in a ListView.
NetworkImageView—builds on ImageLoader and effectively replaces ImageView for situations where your image is being fetched over the network via URL. NetworkImageView also manages canceling pending requests if the view is detached from the hierarchy.
4.3 Use ImageRequest
Create Singleton Class MainActivity.java Main_activity.xml
4.3.1 Create Singleton Class
4.3.1 Create Singleton Class (Con)
4.3.2 main_activity.xml
4.3.3 MainActivity.java
Output
4.4 Using ImageLoader
Create Singleton class main_activity.xml MainActivity.java
4.4.1 Create Singleton Class
4.4.1 Create Singleton Class (Con)
4.4.2 main_activity.xml
4.4.3 MainActivity.java
5. Using Request JSON
Volley provides the following classes for JSON requests: JsonArrayRequest—A request for retrieving a
JSONArray response body at a given URL. JsonObjectRequest—A request for retrieving a
JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.
Note: Both classes are based on the common base class JsonRequest.
Example: Request JSON
Create Singleton Class MainActivity.java Class main_activity.xml Class
Create Singleton Class
MainActivity.java
main_activity.xml
6. Implementing a Custom Request Most requests have ready-to-use implementations in
the toolbox; if your response is a string, image, or JSON, you probably won't need to implement a custom Request.
For cases where you do need to implement a custom request, this is all you need to do: Extend the Request<T> class, where <T>
represents the type of parsed response the request expects.
Implement the abstract methods parseNetworkResponse() and deliverResponse()
parseNetworkResponse Method A Response encapsulates a parsed response for
delivery, for a given type (such as string, image, or JSON).
deliverResponse() Method
Volley calls you back on the main thread with the object you returned in parseNetworkResponse().
Example
Example (Con)
Reference
https://developer.android.com/training/volley/index.html
https://developer.android.com/training/volley/simple.html
https://developer.android.com/training/volley/requestqueue.html
https://developer.android.com/training/volley/request.html
https://developer.android.com/training/volley/request-custom.html