Volley, an essential tool for Android Network Communication-send a standard Request
Volley mainly supports several requests
1. StringRequest: determine a URL to obtain the returned original string.
2. ImageRequest: determine a URL and obtain an image.
3. JsonObjectRequest and JsonArrayRequest: determine a URL and obtain a JSON object or number.
Request an image
Use ImageRequest
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
() { @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 to use ImageLoader and NetworkImageView to effectively load multiple images, such as loading images in ListView.
In the XML file of your layout
Attach Images
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);
As mentioned in the previous article, the RequestQueue is encapsulated so that the image cache is independent from the Activity. When the screen is rotated, the image does not need to be downloaded from the network again, which will not cause a pop-up screen.
The Request JSON is similar to the previous Request. You can view the Code directly.
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
() { @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);