Last active
November 4, 2020 08:06
-
-
Save bitsnaps/d8670b5584e1aa5495f00f31c7fd3d81 to your computer and use it in GitHub Desktop.
Using VolleyPlus to make a request API on Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* VolleySingleton | |
* | |
* This is just a wrapper around [VolleyPlus](https://github.com/DWorkS/VolleyPlus) library (tested with v0.1.4) | |
* You can update the UI without using AsyncTask neither runOnUiThread | |
* It comes with caching and full image caching without third party library, included options to clear cache | |
* It doesn't depend on any other libraries and you can send any type of request (String, JSON...) | |
* It works for both Java and Groovy (it should works for Kotlin as well) | |
* Tested on SdkVersion v19 up to v28. | |
*/ | |
// package ...; | |
import android.content.Context; | |
import android.graphics.drawable.BitmapDrawable; | |
import android.support.v4.util.LruCache; | |
import com.android.volley.Request; | |
import com.android.volley.RequestQueue; | |
import com.android.volley.cache.plus.ImageCache; | |
import com.android.volley.cache.plus.ImageLoader; | |
import com.android.volley.toolbox.Volley; | |
public class VolleySingleton { | |
private static VolleySingleton mInstance; | |
private RequestQueue mRequestQueue; | |
private ImageLoader mImageLoader; | |
private Context mCtx; | |
private boolean mustClearCache; | |
private VolleySingleton(Context context) { | |
mCtx = context; | |
mRequestQueue = getRequestQueue(); | |
mImageLoader = new ImageLoader(mRequestQueue, new ImageCache() { | |
private final LruCache<String, BitmapDrawable> cache = new LruCache<String, BitmapDrawable>(20); | |
@Override | |
public BitmapDrawable getBitmap(String url) { | |
return cache.get(url); | |
} | |
@Override | |
public void putBitmap(String url, BitmapDrawable bitmap) { | |
cache.put(url, bitmap); | |
} | |
@Override | |
public void invalidateBitmap(String url) { | |
cache.remove(url); | |
} | |
@Override | |
public void clear() { | |
cache.evictAll(); | |
} | |
}); | |
} | |
public static synchronized VolleySingleton getInstance(Context context, boolean clearCache) { | |
if (mInstance == null) { | |
mInstance = new VolleySingleton(context); | |
} | |
mInstance.mustClearCache = clearCache; | |
return mInstance; | |
} | |
private RequestQueue getRequestQueue() { | |
if (mRequestQueue == null) { | |
// getApplicationContext() is key, it keeps you from leaking the | |
// Activity or BroadcastReceiver if someone passes one in. | |
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); | |
} | |
return mRequestQueue; | |
} | |
public<T> void addToRequestQueue(Request<T> req, boolean shouldCache) { | |
RequestQueue requestQueue = getRequestQueue(); | |
if (mustClearCache){ | |
requestQueue.getCache().clear(); | |
} | |
req.setShouldCache(shouldCache); | |
requestQueue.add(req); | |
} | |
public<T> void addToRequestQueue(Request<T> req) { | |
addToRequestQueue(req, false); | |
} | |
public ImageLoader getmImageLoader() { | |
return mImageLoader; | |
} | |
} | |
/* | |
// Usage examples: | |
public static String endpoint = "http://HOST_API/v1/api"; | |
// GET Request | |
final TextView tvHello = (TextView) findViewById(R.id.tvHello); | |
tvHello.setText("Calling a Rest API"); | |
// GET Request | |
VolleySingleton.getInstance(getApplicationContext(), true) | |
.addToRequestQueue(new StringRequest(Request.Method.GET, endpoint, | |
new Response.Listener<String>() { | |
@Override | |
public void onResponse(String response) { | |
Log.d("RESULT", response.toString()); | |
tvHello.setText(response.toString()); | |
} | |
}, new Response.ErrorListener() { | |
@Override | |
public void onErrorResponse(VolleyError error) { | |
Log.d("RESULT", "Error: " + error.getMessage()); | |
} | |
}), false); | |
// POST Json Request | |
HashMap<String, String> params = new HashMap<String, String>(); | |
params.put("title", "Post 01"); | |
params.put("body", "How to make an API call"); | |
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, endpoint, | |
new JSONObject(params), | |
new Response.Listener<JSONObject>() { | |
@Override | |
public void onResponse(JSONObject response) { | |
Log.d("RESULT", response.toString()); | |
// if (!response.isNull("title")){ | |
// try { | |
// Log.d("RESULT","Title: " + response.getString("title")); | |
// } catch (JSONException e) { | |
// Log.e("RESULT","JSON Error: " + e.getMessage()); | |
// } | |
// } else { | |
// Log.d("RESULT","response does not have a title key."); | |
// } | |
} | |
}, new Response.ErrorListener() { | |
@Override | |
public void onErrorResponse(VolleyError error) { | |
// hide the progress dialog | |
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show(); | |
Log.d("RESULT", "class="+error.getClass().getSimpleName()+", msg= " + error.getMessage()); | |
} | |
}) { | |
// @Override | |
// public Map<String, String> getHeaders() throws AuthFailureError { | |
// // YOU DO NOT NEED TO OVERWRITE this method | |
// } | |
// @Override | |
// public byte[] getBody() { | |
// YOU DO NOT NEED TO OVERWRITE this method | |
// } | |
@Override // OPTIONAL | |
protected Map<String, String> getParams() { | |
Map<String, String> params = new HashMap<String, String>(); | |
params.put("Content-Type", "application/json"); | |
params.put("Accept", "application/json"); | |
return params; | |
} | |
}; | |
VolleySingleton.getInstance(getApplicationContext(), true) | |
.addToRequestQueue(jsonObjReq, false); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment