Tuesday 8 May 2018

Volley API implementation

dependencies{
//Volley libs
implementation 'com.android.volley:volley:1.0.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.1'
implementation 'com.google.code.gson:gson:2.8.2'
}

android {
//Volley add lines
    useLibrary 'org.apache.http.legacy'
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'

    }
}

=================================================================================================

Create new class LruBitmapCache.java

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {
private static int getDefaultLruCacheSize() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;

return cacheSize;
}

LruBitmapCache() {
this(getDefaultLruCacheSize());
}

private LruBitmapCache(int sizeInKiloBytes) {
super(sizeInKiloBytes);
}

@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);
}
}

=================================================================================================

Create new class MultipartRequest.java

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;

import org.apache.http.HttpEntity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public class MultipartRequest extends Request {
//String KEY_PICTURE = "Post_Image";
private static final String TAG = "MutlipartRequest";

private HttpEntity mHttpEntity;
private final Class mClass;
private Response.Listener mListener;
private Map<String, String> mHeaders;
private Map<String, String> params;

public MultipartRequest(String mainUrl, HttpEntity httpEntity, Class clazz, Map<String, String> headers, Response.Listener listener, Response.ErrorListener errorListener) {
super(Method.POST, mainUrl, errorListener);
mHeaders = headers;
mClass = clazz;
mListener = listener;
mHttpEntity = httpEntity;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Log.d("TAG", "GET PARAM");
return mHeaders != null ? mHeaders : super.getHeaders();
}

@Override
public String getBodyContentType() {
return mHttpEntity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
mHttpEntity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}

@SuppressWarnings("unchecked")
@Override
protected Response parseNetworkResponse(NetworkResponse response) {
String json;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));

} catch (UnsupportedEncodingException e) {
Log.e(TAG, String.format("Encoding problem parsing API response. NetworkResponse:%s",
response.toString()), e);
return Response.error(new ParseError(e));
}
try {
return Response.success(json, HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
Log.e(TAG, String.format("Couldn't API parse JSON response. NetworkResponse:%s",
response.toString()), e);
Log.e(TAG, String.format("Couldn't API parse JSON response. Json dump: %s", json));
return Response.error(new ParseError(e));
}
}

@Override
protected void deliverResponse(Object arg0) {
mListener.onResponse(arg0);
}

}

=================================================================================================

Create new class MyApplication

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * Created by msp on 6/7/16.
 */
public class MyApplication extends Application {
private static MyApplication appInstance;

private static Context mContext;

private static final String KEY_REMEBER = "REMEMBER";
public static final String TAG = MyApplication.class.getSimpleName();
private static final String KEY = "eCommerce";
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

@Override
public void onCreate() {
super.onCreate();
appInstance = this;
MyApplication.mContext = getApplicationContext();

}

public static boolean isConnectivityAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}

public static Context getContext() {
return mContext;
}

public static void setContext(Context mctx) {
mContext = mctx;
}



public static synchronized MyApplication getInstance() {
return appInstance;
}




// for get getRequestQueue object
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}

return mRequestQueue;
}

// for get imageloader object
public com.android.volley.toolbox.ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new com.android.volley.toolbox.ImageLoader(this.mRequestQueue, new LruBitmapCache());
}
return this.mImageLoader;
}

// for add request to queue
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);
}

// for add request queue
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

//for cancle pending request
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}

//for get keyhash of facebook
public void printKeyHash() {
try {
PackageInfo info = getPackageManager().getPackageInfo("com.weddingapp", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("NightLife", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}
}
}

=================================================================================================

Declare Application class in manifest file

android:name=".volley.MyApplication"

=================================================================================================

Create custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#00000000"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

=================================================================================================

Create class VolleyJsonParser


import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.volleydataparsingdemo.R;

import org.json.JSONArray;

import java.util.HashMap;
import java.util.Map;

public class VolleyJsonParser {
    private Context context;
    private String s = null;
    private JSONArray objJson = null;
    private Map<String, String> mparams;
    private VolleyCallback mcallback;
    private VolleyCallback1 mcallback1;
    private Dialog dialog;

    public VolleyJsonParser(Context context) {
        this.context = context;
        initProcessDialog();
    }

    public JSONArray getObjectRequest(final ProgressBar pd, String url, final HashMap<String, String> params, VolleyCallback1 volleyCallback) {
        Log.d("TAG", url);
        // pd.setVisibility(View.VISIBLE);
        this.mparams = params;
        this.mcallback1 = volleyCallback;
        JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                objJson = response;
                mcallback1.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("TAG", "Error: " + error.getMessage());
                Log.e("onErrorResponse", "-->" + error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                return mparams;
            }
        };

        // Adding request to request queue
        MyApplication.getInstance().addToRequestQueue(req, "jarray_req");
        return objJson;
    }

    public void makeStringReq(String url, final HashMap<String, String> params, VolleyCallback volleyCallback) {
        //showDialog();
        this.mparams = params;
        Log.d("TAG", "PARAM " + mparams);
        this.mcallback = volleyCallback;
        StringRequest strReq = new StringRequest(Method.POST, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                // Log.d("TAG", "Response==>" + response.toString());
                // pd.setVisibility(View.INVISIBLE);
//                dismissDialog();
                s = response;
                mcallback.onSuccess(response);

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
//                dismissDialog();
                VolleyLog.d("TAG", "Error: " + error.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                return mparams;
            }

        };

        // Adding request to request queue
        ///strReq.setRetryPolicy(new DefaultRetryPolicy(10000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        strReq.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        MyApplication.getInstance().addToRequestQueue(strReq, "string_req");

    }

    public interface VolleyCallback {
        void onSuccess(String result);
        void onFailure(String jsonResponse);
    }

    public interface VolleyCallback1 {
        void onSuccess(JSONArray result);
        void onFailure(JSONArray jsonResponse);
    }

    public void initProcessDialog() {

        ContextThemeWrapper themedContext;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            themedContext = new ContextThemeWrapper(context, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
        } else {
            themedContext = new ContextThemeWrapper(context, android.R.style.Theme_Light_NoTitleBar);
        }

        dialog = new Dialog(themedContext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.custom_dialog);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialog.setCancelable(false);
    }

    public void showDialog() {
        try {
            if (dialog != null && (!dialog.isShowing())) {
                Log.d("TAG", "SHOW DIALOG");
                dialog.show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void dismissDialog() {
        try {
            if (dialog != null && dialog.isShowing()) {
                Log.d("TAG", "DISMISS DIALOG");
                dialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

=================================================================================================

Activity file
    VolleyJsonParser volleyParser;
    HashMap<String, String> params;
    RequestQueue requestQueue;
    ProductGridAdapter mAdapter;

onCreate {

volleyParser = new VolleyJsonParser(context);
        requestQueue = Volley.newRequestQueue(context);

//      RecyclerView.ItemDecoration itemDecoration1 = new DividerItemDecoration(mContext, LinearLayoutManager.VERTICAL);
//           recyclerView.addItemDecoration(itemDecoration1);

}

private void Forgotpassword() {
        volleyParser.showDialog();
        params = new HashMap<>();
        params.put("api", "forgetpassword");
        params.put("user_Email", "test@test.com");
        volleyParser.makeStringReq("https://swizletime.com/admin/main/frmSwizzleApi.php", params, vForgotpassword);
    }

VolleyJsonParser.VolleyCallback vForgotpassword = new VolleyJsonParser.VolleyCallback() {
        @Override
        public void onSuccess(String result) {
            // TODO Auto-generated method stub
            volleyParser.dismissDialog();
            Log.e("Result", ">>>>>>>>" + result);

            if (result != null) {
                String Result = null;
                try {

                    JSONObject json = new JSONObject(result);

                    String results = json.getString("result");
                    String message = null;
                    message = json.getString("message");
   
    if (results.equalsIgnoreCase("1")) {
//                        showAlertDialog(context, message);
                    } else if (results.equalsIgnoreCase("0")) {
//                        Utility.showAlertDialog(context, message);
                    }

//OR

    ProductResponse productResponse = new Gson().fromJson(response,
                            ProductResponse.class);

    if (productResponse.getStatus().equalsIgnoreCase("success")) {

    }
               
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                //no data found
                Log.e("TAG", " ---No Data found--- ");
            }
        }

        @Override
        public void onFailure(String jsonResponse) {
            // TODO Auto-generated method stub
            Log.e("TAG", "onFailure: " + jsonResponse);
        }
    };

That's it...