Transmitting Network Data Using Volley -Making a Standard Request
来源:互联网 发布:怎样注册淘宝会员名 编辑:程序博客网 时间:2024/05/18 03:22
This lesson describes how to use the common request types that Volley supports:
StringRequest
. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.ImageRequest
. Specify a URL and receive an image in response.JsonObjectRequest
andJsonArrayRequest
(both subclasses ofJsonRequest
). Specify a URL and get a JSON object or array (respectively) in response.
If your expected response is one of these types, you probably won't have to implement a custom request. This lesson describes how to use these standard request types. For information on how to implement your own custom request, seeImplementing a Custom Request.
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. Its main benefit is that Volley's thread scheduling ensures that expensive image operations (decoding, resizing) automatically happen on a worker thread.ImageLoader
—a helper class that handles loading and caching images from remote URLs.ImageLoader
is a an orchestrator for large numbers ofImageRequest
s, for example when putting multiple thumbnails in aListView
.ImageLoader
provides an in-memory cache to sit in front of the normal Volley cache, which is important to prevent flickering. This makes it possible to achieve a cache hit without blocking or deferring off the main thread, which is impossible when using disk I/O.ImageLoader
also does response coalescing, without which almost every response handler would set a bitmap on a view and cause a layout pass per image. Coalescing makes it possible to deliver multiple responses simultaneously, which improves performance.NetworkImageView
—builds onImageLoader
and effectively replacesImageView
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.
Use ImageRequest
Here is an example of using ImageRequest
. It retrieves the image specified by the URL and displays it in the app. Note that this snippet interacts with the RequestQueue
through a singleton class (see Setting Up a RequestQueue for more discussion of this topic):
ImageView mImageView;String url = "http://i.imgur.com/7spzG.png";mImageView = (ImageView) findViewById(R.id.myImage);...// Retrieves an image specified by the URL, displays it in the UI.ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() { @Override public void onResponse(Bitmap bitmap) { mImageView.setImageBitmap(bitmap); } }, 0, 0, null, new Response.ErrorListener() { public void onErrorResponse(VolleyError error) { mImageView.setImageResource(R.drawable.image_load_error); } });// Access the RequestQueue through your singleton class.MySingleton.getInstance(this).addToRequestQueue(request);
Use ImageLoader and NetworkImageView
You can use ImageLoader
and NetworkImageView
in concert to efficiently manage the display of multiple images, such as in a ListView
. In your layout XML file, you use NetworkImageView
in much the same way you would use ImageView
, for example:
<com.android.volley.toolbox.NetworkImageView android:id="@+id/networkImageView" android:layout_width="150dp" android:layout_height="170dp" android:layout_centerHorizontal="true" />
You can use ImageLoader
by itself to display an image, for example:
ImageLoader mImageLoader;ImageView mImageView;// The URL for the image that is being loaded.private static final String IMAGE_URL = "http://developer.android.com/images/training/system-ui.png";...mImageView = (ImageView) findViewById(R.id.regularImageView);// Get the ImageLoader through your singleton class.mImageLoader = MySingleton.getInstance(this).getImageLoader();mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView, R.drawable.def_image, R.drawable.err_image));
However, NetworkImageView
can do this for you if all you're doing is populating an ImageView
. For example:
ImageLoader mImageLoader;NetworkImageView mNetworkImageView;private static final String IMAGE_URL = "http://developer.android.com/images/training/system-ui.png";...// Get the NetworkImageView that will display the image.mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);// Get the ImageLoader through your singleton class.mImageLoader = MySingleton.getInstance(this).getImageLoader();// Set the URL of the image that should be loaded into this view, and// specify the ImageLoader that will be used to make the request.mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);
The above snippets access the RequestQueue
and the ImageLoader
through a singleton class, as described inSetting Up a RequestQueue. This approach ensures that your app creates single instances of these classes that last the lifetime of your app. The reason that this is important for ImageLoader
(the helper class that handles loading and caching images) is that the main function of the in-memory cache is to allow for flickerless rotation. Using a singleton pattern allows the bitmap cache to outlive the activity. If instead you create the ImageLoader
in an activity, the ImageLoader
would be recreated along with the activity every time the user rotates the device. This would cause flickering.
Example LRU cache
The Volley toolbox provides a standard cache implementation via the DiskBasedCache
class. This class caches files directly onto the hard disk in the specified directory. But to use ImageLoader
, you should provide a custom in-memory LRU bitmap cache that implements the ImageLoader.ImageCache
interface. You may want to set up your cache as a singleton; for more discussion of this topic, see Setting Up a RequestQueue.
Here is a sample implementation for an in-memory LruBitmapCache
class. It extends the LruCache
class and implements the ImageLoader.ImageCache
interface:
import android.graphics.Bitmap;import android.support.v4.util.LruCache;import android.util.DisplayMetrics;import com.android.volley.toolbox.ImageLoader.ImageCache;public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache { public LruBitmapCache(int maxSize) { super(maxSize); } public LruBitmapCache(Context ctx) { this(getCacheSize(ctx)); } @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight(); } @Override public Bitmap getBitmap(String url) { return get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); } // Returns a cache size equal to approximately three screens worth of images. public static int getCacheSize(Context ctx) { final DisplayMetrics displayMetrics = ctx.getResources(). getDisplayMetrics(); final int screenWidth = displayMetrics.widthPixels; final int screenHeight = displayMetrics.heightPixels; // 4 bytes per pixel final int screenBytes = screenWidth * screenHeight * 4; return screenBytes * 3; }}
Here is an example of how to instantiate an ImageLoader
to use this cache:
RequestQueue mRequestQueue; // assume this exists.ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache( LruBitmapCache.getCacheSize()));
Request JSON
Volley provides the following classes for JSON requests:
JsonArrayRequest
—A request for retrieving aJSONArray
response body at a given URL.JsonObjectRequest
—A request for retrieving aJSONObject
response body at a given URL, allowing for an optionalJSONObject
to be passed in as part of the request body.
Both classes are based on the common base class JsonRequest
. You use them following the same basic pattern you use for other types of requests. For example, this snippet fetches a JSON feed and displays it as text in the UI:
TextView mTxtDisplay;ImageView mImageView;mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);String url = "http://my-json-feed";JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { mTxtDisplay.setText("Response: " + response.toString()); }}, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO Auto-generated method stub }});// Access the RequestQueue through your singleton class.MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);For an example of implementing a custom JSON request based on Gson, see the next lesson, Implementing a Custom Request.
- Transmitting Network Data Using Volley -Making a Standard Request
- Transmitting Network Data Using Volley - Sending a Simple Request
- Transmitting Network Data Using Volley -Implementing a Custom Request
- Transmitting Network Data Using Volley 之Sending a Simple Request
- Transmitting Network Data Using Volley - Setting Up a RequestQueue
- 跟Google 学代码:Transmitting Network Data Using Volley
- Making a Standard Request
- Transmitting Network Data Using Volley(使用Volley框架传输网络数据)
- Transmitting Network Data Using Volley - Volley is an HTTP library that makes networking for Android
- Android训练课程(Android Training) - 使用Volley传输网络数据(Transmitting Network Data Using Volley)
- volley创建标准的网络请求(Making a Standard Request)
- using ViewPager making a flush
- multipart data using Android Volley
- How To Capture Data Packets On A Network Using Wireshark (a. k. a. Ethereal)
- Making plain binary files using a C compiler(ZT)
- Making plain binary files using a C compiler (i386+)
- Making plain binary files using a C compiler (i386+)
- Transmitting Audio and Video using RTP
- Photoshop入门教程(六):通道
- 周岁和虚岁的区别
- 【Servlet】根据MVC思想设计用户登陆、用户注册、修改密码系统
- BeginPaint和GetDC有什么区别?
- Emacs 的简单设置
- Transmitting Network Data Using Volley -Making a Standard Request
- Transmitting Network Data Using Volley -Implementing a Custom Request
- android 项目实战——打造超级课程表一键提取课表功能
- iOS 单例的使用
- 661992156835756868
- Install Adobe Flash plugin in Ubuntu 14.04
- Java中super的几种用法并与this的区别
- BeginPaint和GetDC有什么区别?
- HTML5APP实战(1): 围住神经猫(一)