Content
1) android volley post request with parameters. This example passing two parameters "foo1" and "bar1" with values "foo1qq" and "bar1qq" respectively stored in JSONObject to
POST JsonObjectRequest.
2) How to Use Volley Singleton class in android
3) Return response data from function "onResponse" in Volley Library using
interface VolleyCallback
4) How to set DefaultRetryPolicy and TimeOut using method setRetryPolicy for volley JsonObjectRequest in android.
5) how to check internet connection in android programmatically before making
POST JsonObjectRequest. So don't forgot to add beow permission in AndroidManifest.xml of your app:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
MainActivity.java
package com.example.espl.volleypostjsonrequest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
String URL="https://postman-echo.com/post";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NetworkUtility.makeJsonObjReq(URL, "", new VolleyCallBack() {
@Override
public void onSuccess(JSONObject result) {
Log.e("JsonObjectRequestRespo", "::" + result.toString());
}
});
}
}
NetworkUtility.java
package com.example.espl.volleypostjsonrequest;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONException;
import org.json.JSONObject;
public class NetworkUtility {
private static int timeOut = 90000;
/**
* @param2 - data (Params of service)
* Method Name :- makeJsonObjReq
* <p>
* Decription : - this function is used for service call
*
* @param url the url
* @param data the data
* @param volleyCallBack the volley call back
* @param1 - url (Web service url)
* @param3 - volleyCallBack (Reasult call back while user get success response at that time this will call and return json object reasons)
*/
public static void makeJsonObjReq(final String url, final String tag, final VolleyCallBack volleyCallBack) {
// check internet connection. if internet is available then will call this method else display internet connection Message
if (checkInternet(Application.get())) {
if (tag != null) {
Log.e("cancel the request", "::" + "cancelPending request called");
VolleySingleton.getInstance(Application.get()).cancelPendingRequests(tag);
}
JSONObject map = new JSONObject();
try {
map.put("foo1", "foo1qq");
map.put("bar1", "bar1qq");
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request_json = new JsonObjectRequest(Request.Method.POST, url, map, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
volleyCallBack.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("JsonObjectRequestRespo", "::" + error.toString());
}
}
);
request_json.setRetryPolicy(new DefaultRetryPolicy(
timeOut,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(Application.get()).addToRequestQueue(request_json);
}
}
public static boolean checkInternet(Context context) {
try {
ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
boolean status = conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected();
if (status)
return status;
else {
Toast.makeText(context, "Internet connection is not available.",Toast.LENGTH_SHORT).show();
return status;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
VolleySingleton.java
package com.example.espl.volleypostjsonrequest;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
/**
* Singleton volley to populate request into single queue.
* <p/>
* Sketch Project Studio
* Created by Angga on 22/04/2016 22.58.
*/
public class VolleySingleton {
private static VolleySingleton mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
/**
* Private constructor, only initialization from getInstance.
*
* @param context parent context
*/
private VolleySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> cache = new LruBitmapCache(mCtx);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
/**
* Singleton construct design pattern.
*
* @param context parent context
* @return single instance of VolleySingleton
*/
public static synchronized VolleySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleySingleton(context);
}
return mInstance;
}
/**
* Get current request queue.
*
* @return RequestQueue
*/
public 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;
}
/**
* Add new request depend on type like string, json object, json array request.
*
* @param req new request
* @param <T> request type
*/
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
/**
* Get image loader.
*
* @return ImageLoader
*/
// public ImageLoader getImageLoader() {
// return mImageLoader;
// }
// /**
// * Cancels all pending requests by the specified TAG, it is important
// * to specify a TAG so that the pending/ongoing requests can be cancelled.
// *
// * @param tag
// */
public void cancelPendingRequests(String tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
VolleyCallBack.java
package com.example.espl.volleypostjsonrequest;
import org.json.JSONObject;
/**
* Created by espl on 27/9/16.
*/
public interface VolleyCallBack {
/**
* On success.
*
* @param result the result
*/
// on success result
void onSuccess(JSONObject result);
}
LruBitmapCache.java
package com.example.espl.volleypostjsonrequest;
import android.content.Context;
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));
}
// 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;
}
@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);
}
}
Application.java
package com.example.espl.volleypostjsonrequest;
/**
* Created by espl on 27/9/16.
*/
public class Application extends android.app.Application {
// public static DeviceName.DeviceInfo deviceInfo;
private static Application _instance;
@Override
public void onCreate() {
super.onCreate();
_instance = this;
}
public static Application get() {
return _instance;
}
}