Volley.java
public class Volley { private static Volley mInstance; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private static Context mCtx; public static final String TAG = Volley.class.getSimpleName(); private Volley(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); @Override
public Bitmap getBitmap(String url) { return cache.get(url); } @Override
public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); //Added to make image upload and download faster!
//mImageLoader.setBatchedResponseDelay(0); } public static synchronized Volley getInstance(Context context) { if (mInstance == null) { mInstance = new Volley(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024); Network network = new BasicNetwork(new HurlStack()); //Changed over here, changed default pool size!
//This worked out for making it work fast in older devices also!
//Still not working (fastly in previous devices)
mRequestQueue = new RequestQueue(cache, network, 10); // Don't forget to start the volley request queue
mRequestQueue.start(); //mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
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 ImageLoader getImageLoader() { return mImageLoader; } }
VolleyNetworkRequest.java
import android.content.Intent; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyLog; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; public class VolleyNetworkRequest<T> extends Request<T> { public static final int DEFAULT_TIMEOUT_MS = 20000; public static final int DEFAULT_MAX_RETRIES = 0; private static final String TAG = "--MultipartRequest--"; // private String FILE_PART_NAME = "image";// private List<String> FILE_PART_NAME; private final Response.Listener<T> mListener; private final Gson gson = new Gson(); //private final File mImageFile; protected Map<String, String> headers; boolean isPojo; private MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create(); private Map<String, String> stringData; private Context ctxt; private Class<T> clazz; // private ArrayList<File> mFilePart; private HashMap<String, File> mFilePart; private boolean isClosed; public VolleyNetworkRequest(String url, ErrorListener errorListener, Listener<T> listener, File imageFile) { super(Method.POST, url, errorListener); mListener = listener; //mImageFile = imageFile; buildMultipartEntity(); } public VolleyNetworkRequest(Context ctxt, String url, ErrorListener errorListener, Listener<T> listener, Map<String, String> stringData, HashMap<String, File> fileParam, Class clazz, Map<String, String> headers, boolean isPojo) { super(Method.POST, url, errorListener); setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); this.ctxt = ctxt; mListener = listener; //mImageFile = imageFile; this.stringData = stringData; this.clazz = clazz; mFilePart = fileParam; // this.FILE_PART_NAME = file_param_name; this.headers = headers; this.isPojo = isPojo; /*if (showDialog == true) { //showProgressBarDialog(); showProgressDialog(); }*/ buildMultipartEntity(); } @Override public Map<String, String> getHeaders() throws AuthFailureError { /*Map<String, String> headers = super.getHeaders(); if (headers == null || headers.equals(Collections.emptyMap())) { headers = new HashMap<String, String>(); } headers.put("Accept", "application/json"); return headers;*/// return headers != null ? headers : VolleyGlobal.getInstance(ctxt).getHeaders(); return headers; } /** * mFilePart and FILE_PART_NAME size must be equal else it will throw error */ private void buildMultipartEntity() { if (null != mFilePart) { for (Map.Entry<String, File> entry : mFilePart.entrySet()) { // mBuilder.addPart(entry.getKey(), new FileBody(entry.getValue())); mBuilder.addBinaryBody(entry.getKey(), entry.getValue(), ContentType.create("image/jpeg"), entry.getValue().getName()); } } /* private void buildMultipartEntity() { if (null != mFilePart) { for (int i = 0; i < mFilePart.size(); i++) { mBuilder.addBinaryBody(FILE_PART_NAME.get(i), mFilePart.get(i), ContentType.create("image/jpeg"), mFilePart.get(i).getName()); } }*/ mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); mBuilder.setLaxMode().setBoundary("xx").setCharset(Charset.forName("UTF-8")); if (null != stringData) { try { for (Map.Entry<String, String> entry : stringData.entrySet()) { //entity.addPart(postEntityModel.getName(), new StringBody(postEntityModel.getValue(), ContentType.TEXT_PLAIN)); mBuilder.addTextBody(entry.getKey(), entry.getValue()); } } catch (Exception e) { Log.e(TAG, "buildMultipartEntity: =" + e.getMessage()); } } } @Override public String getBodyContentType() { String contentTypeHeader = mBuilder.build().getContentType().getValue(); return contentTypeHeader; } @Override public byte[] getBody() throws AuthFailureError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { mBuilder.build().writeTo(bos); } catch (IOException e) { VolleyLog.e("IOException writing to ByteArrayOutputStream bos, building the multipart request."); } return bos.toByteArray(); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); Log.e(TAG, "parseNetworkResponse: =" + json); JSONObject jsonObject = new JSONObject(json); if (isPojo) { T myPojo = gson.fromJson(json, clazz); return Response.success(myPojo, HttpHeaderParser.parseCacheHeaders(response)); //it will return pojo class } return (Response<T>) Response.success(json, HttpHeaderParser.parseCacheHeaders(response));// it will return String } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } catch (Exception e) { return Response.error(new ParseError(e)); } /* T result = null; return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));*/ } @Override protected void deliverResponse(T response) { mListener.onResponse(response); } }
Comments
Post a Comment