Skip to main content

Volley for client and server interaction (Android)

Volley provides client and server interaction with QUEUE basis, each and every request process separately, we can cancel our request from QUEUE.

HERE is a code sample for Volley with json request format.

GenerateRequest.java

--------------------------------------------------------------------
package com.entrata.maintenance.network_communication.networkutils;
import android.content.Context;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.entrata.maintenance.application.ERPUserDefaults;
import com.entrata.maintenance.network_communication.networkconstant.NetworkConstant;
import com.entrata.maintenance.network_communication.networkexception.Error;
import com.entrata.maintenance.network_communication.networkutil.SubdomainChange;
import com.entrata.maintenance.utils.Logger;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class GenerateRequest {
    //region Field Declaration
    private static final String METHOD = "method";
    private static final String NAME = "name";
    private static final String AUTHORIZATION = "Authorization";
    private static final String AUTHORIZATION_DEV = "Authorization_Dev";
    private static final String RESULT = "result";
    private static final String ERROR = "error";
    private static final String TAG = GenerateRequest.class.getName();
    private static final String RESPONSE = "response";
    private NetworkResultListener networkResultListener;
    //endregion Field Declaration
    /**
     * @param request
     */
    public void addRequestToQueue(Context context, final JSONObject request, int requestType) throws JSONException, AuthFailureError {
        if (null != context) {
            final SubdomainChange subdomainChange = new SubdomainChange(context);
            final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestType, request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN)  ? subdomainChange.replaceLogin() : subdomainChange.replace(), request, success, error) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> header = new HashMap<>();
                    try {
                        if (!subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "").equals("") && !request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN)) {
                            header.put(AUTHORIZATION, String.format("Bearer %s", subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "")));
                            header.put("Content-Type", "application/json");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return header;
                }
            };
            NetworkHandler.getInstance(context).addToRequestQueue(jsonObjectRequest);
        }
    }
    /**
     * @param request
     */
    public JsonObjectRequest addRequestToQueues(Context context, final JSONObject request, int requestType) throws JSONException, AuthFailureError {
        JsonObjectRequest jsonObjectRequest = null;
        if (null != context) {
            final SubdomainChange subdomainChange = new SubdomainChange(context);
            jsonObjectRequest = new JsonObjectRequest(requestType, request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN) || request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.FORGOT_COMPANY_USER_PASSWORD) ? subdomainChange.replaceLogin() : subdomainChange.replace(), request, success, error) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> header = new HashMap<>();
                    try {
                        if (!subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "").equals("") && !request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN)) {
                            header.put(AUTHORIZATION, String.format("Bearer %s", subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "")));
                            header.put("Content-Type", "application/json");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return header;
                }
            };
            NetworkHandler.getInstance(context).addToRequestQueue(jsonObjectRequest);
        }
        return jsonObjectRequest;
    }
    /**
     * @param networkResultListener
     */
    public void setNetworkResultListener(NetworkResultListener networkResultListener) {
        this.networkResultListener = networkResultListener;
    }
    Response.Listener<JSONObject> success = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                if (null != response) {
                    JSONObject jsonObject = response;
                    if (null != jsonObject) {
                        if (jsonObject.getJSONObject(RESPONSE).has(RESULT)) {
                            networkResultListener.onSuccess(response);
                        } else if (jsonObject.getJSONObject(RESPONSE).has(ERROR)) {
                            Error error = new Gson().fromJson(jsonObject.getJSONObject(RESPONSE).getJSONObject(ERROR).toString(), Error.class);
                            networkResultListener.onError(error);
                        } else {
                            networkResultListener.onFailure(response);
                        }
                    } else {
                        networkResultListener.onFailure(response);
                    }
                } else {
                    networkResultListener.onFailure(response);
                }
            } catch (JSONException e) {
                Logger.print(TAG, e.toString());
            }
        }
    };
    Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            try {
                networkResultListener.onFailure(error);
            } catch (JSONException e) {
                Logger.print(TAG, e.toString());
            }
        }
    };
}

---------------------------------------------------------------------------

NetworkHandler.java

-------------------------------------------------------------------------
package com.entrata.maintenance.network_communication.networkutils;

import android.content.Context;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;
import com.entrata.maintenance.utils.Logger;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
 * @author Tatyabhau Chavan
 * @since 23/12/2016
 */
public class NetworkHandler {
    private static final String TAG = NetworkHandler.class.getName();
    private static RequestQueue requestQueue;
    private Context context;
    private static volatile NetworkHandler instance;
    private SSLSocketFactory sslFactory;
    private static final int MY_SOCKET_TIMEOUT_MS = 30000;
    private NetworkHandler(Context context) {
        this.context = context;
    }
    /**
     * @param context
     * @return instance
     */
    public static NetworkHandler getInstance(Context context) {
        NetworkHandler result = instance;
        if (null == result) {
            synchronized (NetworkHandler.class) {
                result = instance;
                if (null == result) {
                    instance = result = new NetworkHandler(context);
                }
            }
        }
        return instance;
    }
    /**
     * @return request queue
     */
    public synchronized RequestQueue getRequestQueue() {
        HurlStack hurlStack = new HurlStack(null, createSslSocketFactory());
        requestQueue = Volley.newRequestQueue(context.getApplicationContext(), hurlStack);
       // requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        return requestQueue;
    }
    /**
     * @return factory
     */
    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } catch (NoSuchAlgorithmException e) {
            Logger.print(e.toString(), TAG);
        } catch (KeyManagementException e) {
        }
        return sslSocketFactory;
    }
    private static class NullHostNameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    /**
     * @param request
     * @param <T>
     */
    public <T> void addToRequestQueue(Request<T> request) {
        request.setRetryPolicy(new DefaultRetryPolicy(
                MY_SOCKET_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(request);
    }

}
------------------------------------------------------------------
NetworkResultListener.java
------------------------------------------------------------------
package com.entrata.maintenance.network_communication.networkutils;
import com.entrata.maintenance.network_communication.networkexception.Error;
import org.json.JSONException;

public interface NetworkResultListener<T> {
    void onSuccess(T success) throws JSONException;
    void onFailure(T failure) throws JSONException;
    void onError(Error error);
}




Comments

Popular posts from this blog

Custom camera using SurfaceView android with autofocus & auto lights & more

Custom camera using SurfaceView android with autofocus & auto lights & much more /**  * @author Tatyabhau Chavan  *  */ public class Preview extends SurfaceView implements SurfaceHolder.Callback {     private SurfaceHolder mHolder;     private Camera mCamera;     public Camera.Parameters mParameters;     private byte[] mBuffer;     private Activity mActivity;     // this constructor used when requested as an XML resource     public Preview(Context context, AttributeSet attrs) {         super(context, attrs);         init();     }     public Preview(Context context) {         super(context);         init();     }     public Camera getCamera() {         return this.mCamera;     }     public void init() {         // Install a SurfaceHolder.Callback so we get notified when the         // underlying surface is created and destroyed.         mHolder = getHolder();         mHolder.addCallback(this);         mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);     }     public

Get Android phone call history/log programmatically

Get Android phone call history/log programmatically To get call history programmatically first add read conact permission in Manifest file : <uses-permission android:name="android.permission.READ_CONTACTS" /> Create xml file. Add the below code in xml file : <Linearlayout android:layout_height="fill_parent"  android:layout_width="fill_parent" android:orientation="vertical"> <Textview android:id="@+id/call" android:layout_height="fill_parent" android:layout_width="fill_parent"> </Textview> </Linearlayout> Now call the getCallDetails() method in java class : private void getCallDetails() { StringBuffer sb = new StringBuffer(); Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null); int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE ); int date = managedCur

Bitmap scalling and cropping from center

How to Bitmap scalling and cropping from center? public class ScalingUtilities {     /**      * Utility function for decoding an image resource. The decoded bitmap will      * be optimized for further scaling to the requested destination dimensions      * and scaling logic.      *      * @param res      *            The resources object containing the image data      * @param resId      *            The resource id of the image data      * @param dstWidth      *            Width of destination area      * @param dstHeight      *            Height of destination area      * @param scalingLogic      *            Logic to use to avoid image stretching      * @return Decoded bitmap      */     public static Bitmap decodeResource(Resources res, int resId, int dstWidth,             int dstHeight, ScalingLogic scalingLogic) {         Options options = new Options();         options.inJustDecodeBounds = true;         BitmapFactory.decodeResource(res, resId, options);