RequestQueue requestQueue =
Volley.newRequestQueue(context.getApplicationContext());
StringRequest request = new StringRequest(
Request.Method.GET,
url,
listener,
errorListener);
Response.Listener<String> listener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
L.d("Success Response: " + response.toString());
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null) {
L.d("Error Response code: " +
error.networkResponse.statusCode);
}
}
};
requestQueue.add(request);
public class CookieRequest extends StringRequest {
private String mCookieValue;
public CookieRequest(String url, String cookieValue,
Response.Listener<String> listener,
Response.ErrorListener errorListener) {
super(Method.GET, url, listener, errorListener);
mCookieValue = cookieValue;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("Cookie", mCookieValue);
return map;
}
}
@Override getParams() method
StringRequest request = new StringRequest(
Request.Method.POST,
url,
listener,
errorListener) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "Jon Doe");
map.put("age", "21");
return map;
}
};
StringRequest request = new StringRequest(
Request.Method.GET,
url,
listener,
errorListener);
request.setRetryPolicy(
new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, // 2500
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 1
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); //1f
StringRequest request = new StringRequest(
Request.Method.GET,
url,
listener,
errorListener) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return createBasicAuthHeader("user", "passwd");
}
};
Map<String, String>
createBasicAuthHeader(String username, String password) {
Map<String, String> headerMap = new HashMap<String, String>();
String credentials = username + ":" + password;
String base64EncodedCredentials =
Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headerMap.put("Authorization", "Basic " + base64EncodedCredentials);
return headerMap;
}
StringRequest request1 = new StringRequest(...);
request1.setTag("weather-screen");
StringRequest request2 = new StringRequest(...);
request2.setTag("weather-screen");
requestQueue.add(request1);
requestQueue.add(request2);
requestQueue.cancelAll("weather-screen");
public class RequestProxy {
private RequestQueue mRequestQueue;
// package access constructor
RequestProxy(Context context) {
mRequestQueue =
Volley.newRequestQueue(context.getApplicationContext());
}
public void login() {
// login request
}
public void weather() {
// weather request
}
}
public class RequestManager {
private static RequestManager instance;
private RequestProxy mRequestProxy;
private RequestManager(Context context) {
mRequestProxy = new RequestProxy(context);
}
public RequestProxy doRequest() {
return mRequestProxy;
}
.. init methods see part 2
}
public static synchronized RequestManager getInstance(Context context) {
if (instance == null) {
instance = new RequestManager(context);
}
return instance;
}
public static synchronized RequestManager getInstance() {
if (instance == null) {
throw new IllegalStateException
(RequestManager.class.getSimpleName() +
" is not initialized, call getInstance(..) method first.");
}
return instance;
}
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// RequestManager initialization
RequestManager.getInstance(getApplicationContext());
}
}
RequestManager.getInstance().doRequest().login(..);
RequestManager.getInstance().doRequest().weather(..);
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/imgAvatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
NetworkImageView imgAvatar =
(NetworkImageView) findViewById(R.id.imgAvatar);
imageView.setImageUrl(url, imageLoader);
imageView.setDefaultImageResId(..);
imageView.setErrorImageResId(..);
ImageLoader imageLoader =
new ImageLoader(Volley.newRequestQueue(context), imageCache);
public class BitmapLruCache
extends LruCache<String, Bitmap>
implements ImageLoader.ImageCache {
public BitmapLruCache() {
this(getDefaultLruCacheSize());
}
public BitmapLruCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}
.. more methods see part 2
public static int getDefaultLruCacheSize() {
final int maxMemory =
(int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
return cacheSize;
}
}
@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);
}
ImageLoader.ImageCache imageCache = new BitmapLruCache();
ImageLoader imageLoader = new ImageLoader(Volley.newRequestQueue(context), imageCache);
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/imgAvatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
NetworkImageView imgAvatar =
(NetworkImageView) findViewById(R.id.imgAvatar);
imageView.setImageUrl(url, imageLoader);
Volley.newRequestQueue(context)
// Inside newRequestQueue method
File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
Method description: getCacheDir()
You should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space.
Volley.newRequestQueue(context)
// Default maximum disk usage in bytes. private static final int DEFAULT_DISK_USAGE_BYTES = 25 * 1024 * 1024;
// Default cache folder name private static final String DEFAULT_CACHE_DIR = "photos";
private static RequestQueue newRequestQueue(Context context) {
// define cache folder
File rootCache = context.getExternalCacheDir(); if (rootCache == null) { L.w("Can't find External Cache Dir, " + "switching to application specific cache directory"); rootCache = context.getCacheDir(); }
File cacheDir = new File(rootCache, DEFAULT_CACHE_DIR); cacheDir.mkdirs();
.. more lines of code see part 2
HttpStack stack = new HurlStack();
Network network = new BasicNetwork(stack);
DiskBasedCache diskBasedCache =
new DiskBasedCache(cacheDir, DEFAULT_DISK_USAGE_BYTES);
RequestQueue queue = new RequestQueue(diskBasedCache, network);
queue.start();
return queue;
}
ImageLoader.ImageCache imageCache = new BitmapLruCache();
ImageLoader imageLoader =
new ImageLoader(newRequestQueue(context), imageCache);
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/imgAvatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"/>
NetworkImageView imgAvatar =
(NetworkImageView) findViewById(R.id.imgAvatar);
imageView.setImageUrl(url, imageLoader);
new ImageRequest(
url,
listener,
maxWidth,
maxHeight,
decodeConfig,
errorListener);
Response.Listener<Bitmap> listener = new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
// use your bitmap
}
};
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String result = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(result,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}