com.instiwork.RegistrationActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.instiwork.RegistrationActivity.java

Source

package com.instiwork;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.ads.conversiontracking.AdWordsRemarketingReporter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.android.gms.iid.InstanceID;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.instiwork.Logger.Logger;
import com.instiwork.adpaters.CountrySpinnerAdapter;
import com.instiwork.adpaters.LicenseHorizontalAdapter;
import com.instiwork.application.InstiworkApplication;
import com.instiwork.constants.InstiworkConstants;
import com.instiwork.customview.RobotoBold;
import com.instiwork.customview.RobotoLight;
import com.instiwork.helper.ImageCompress;
import com.instiwork.helper.PermissionUtils;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

public class RegistrationActivity extends AppCompatActivity
        implements ActivityCompat.OnRequestPermissionsResultCallback, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    RobotoLight license;
    LinearLayout ll_license, ll_image_selection;
    RecyclerView selecteddata;
    TextView dateOfBirth;
    EditText fstName, lastname, email, email_confirm, password, conformPassword, mobile;
    RadioGroup gender;
    ImageView pro_img;
    String genderData = "";
    String gcmToken = "";
    SharedPreferences appSharedPref = null;
    public final String TAG = "RegistrationActivity";
    ProgressDialog pDialogOut;
    LicenseHorizontalAdapter licenseHorizontalAdapter;
    String imgPath = "", license_ = "", result = "", status = "", message = "";
    LinkedList<JSONObject> licenseLinkedList;
    //--------FB
    CallbackManager callbackManager;
    String fbAccessToken = "";

    // Location Latitude and Longitude
    GoogleMap googleMapFinal = null;
    protected GoogleApiClient mGoogleApiClient;
    protected Location mLastLocation = null;
    GoogleMapOptions gMapOption = null;
    final int MY_PERMISSIONS_REQUEST_READ = 1;
    String LOCATION_LATITUDE = "", LOCATION_LONGITUDE = "";
    private boolean mPermissionDenied = false;

    ProgressBar countryPbar;
    Spinner country_spinner;
    String country_2_code = "", country_id = "";
    LinkedList<JSONObject> objectsCountry;

    Dialog mBottomSheetDialogTermsUse = null;
    ProgressBar pBarPrivacyPolicy, pBarTermsUse;
    RobotoLight txtPrivacyPolicy, txtTermsUse, txt_fees;
    RobotoBold txt_terms_conditions;
    WebView webViewTermsUse;

    String currentCountry = "";

    public void dialogTermsUse() {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_terms_use, null);
        mBottomSheetDialogTermsUse = new Dialog(RegistrationActivity.this, R.style.MaterialDialogSheet);
        mBottomSheetDialogTermsUse.setContentView(view);
        mBottomSheetDialogTermsUse.setCancelable(false);
        mBottomSheetDialogTermsUse.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBottomSheetDialogTermsUse.getWindow()
                    .addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            mBottomSheetDialogTermsUse.getWindow().setStatusBarColor(Color.parseColor("#536942"));
        }
        mBottomSheetDialogTermsUse.getWindow().setGravity(Gravity.BOTTOM);
        mBottomSheetDialogTermsUse.show();

        view.findViewById(R.id.back_me_dlog_payment).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mBottomSheetDialogTermsUse.dismiss();
            }
        });

        pBarTermsUse = (ProgressBar) view.findViewById(R.id.pbar_terms_use);
        //        txtTermsUse = (RobotoLight) view.findViewById(R.id.txt_terms_use);

        webViewTermsUse = (WebView) view.findViewById(R.id.webv);
        webViewTermsUse.getSettings().setJavaScriptEnabled(true);
        webViewTermsUse.setVisibility(View.GONE);

        getTermsUse(InstiworkConstants.URL_DOMAIN + "Privacy_control");

        mBottomSheetDialogTermsUse.setOnKeyListener(new DialogInterface.OnKeyListener() {

            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
                        mBottomSheetDialogTermsUse.dismiss();
                        return true;
                    }
                return false;
            }
        });
    }

    public void getTermsUse(final String URL) {
        Logger.showMessage(TAG, "Privacy " + URL);

        JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        pBarTermsUse.setVisibility(View.GONE);
                        webViewTermsUse.setVisibility(View.VISIBLE);
                        try {
                            if (response.getString("status").equalsIgnoreCase("Success")) {
                                //                                txtTermsUse.setText(Html.fromHtml(response.getString("Terms")));
                                webViewTermsUse.loadDataWithBaseURL(URL, response.getString("Terms"), "text/html",
                                        "UTF-8", null);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            //                            txtTermsUse.setText("");
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        pBarTermsUse.setVisibility(View.GONE);
                        if (volleyError instanceof NoConnectionError) {
                            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                    RegistrationActivity.this);
                            builder.setTitle("Instiwork");
                            builder.setMessage("You do not have internet connection!");
                            builder.setPositiveButton("retry", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                    pBarTermsUse.setVisibility(View.VISIBLE);
                                    webViewTermsUse.setVisibility(View.GONE);
                                    getTermsUse(URL);
                                }
                            });
                            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
                            builder.setCancelable(false);
                            builder.show();
                        }
                    }
                });
        jsonReq.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        InstiworkApplication.getInstance().addToRequestQueue(jsonReq);
    }

    @Override
    public void onBackPressed() {
        try {
            if (getIntent().getStringExtra("FROM").equalsIgnoreCase("LoginActivity")) {
                Intent backIntent = new Intent(RegistrationActivity.this, LoginActivity.class);
                startActivity(backIntent);
                finish();
            } else if (getIntent().getStringExtra("FROM").equalsIgnoreCase("SigninOrSignUpActivity")) {
                Intent backIntent = new Intent(RegistrationActivity.this, SigninOrSignUpActivity.class);
                startActivity(backIntent);
                finish();
            } else {
                Intent backIntent = new Intent(RegistrationActivity.this, SigninOrSignUpActivity.class);
                startActivity(backIntent);
                finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //            super.onBackPressed();
            Intent backIntent = new Intent(RegistrationActivity.this, SigninOrSignUpActivity.class);
            startActivity(backIntent);
            finish();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
        callbackManager = CallbackManager.Factory.create();

        pDialogOut = new ProgressDialog(RegistrationActivity.this);
        pDialogOut.setMessage("Signing up...");
        pDialogOut.setCancelable(false);
        pDialogOut.setCanceledOnTouchOutside(false);

        appSharedPref = getSharedPreferences("INSTIWORD", Context.MODE_PRIVATE);

        Picasso.with(getApplicationContext()).load(R.drawable.registrationbg).fit().centerCrop()
                .into((ImageView) findViewById(R.id.regbg));

        dateOfBirth = (TextView) findViewById(R.id.dateofbirth);
        license = (RobotoLight) findViewById(R.id.license);
        ll_license = (LinearLayout) findViewById(R.id.ll_license);
        selecteddata = (RecyclerView) findViewById(R.id.selecteddat);
        selecteddata.setVisibility(View.GONE);
        gender = (RadioGroup) findViewById(R.id.gender_group);

        fstName = (EditText) findViewById(R.id.first_name);
        lastname = (EditText) findViewById(R.id.last_name);
        email = (EditText) findViewById(R.id.email);
        email_confirm = (EditText) findViewById(R.id.email_confirm);
        password = (EditText) findViewById(R.id.password);
        conformPassword = (EditText) findViewById(R.id.con_password);
        mobile = (EditText) findViewById(R.id.mobile);

        ll_image_selection = (LinearLayout) findViewById(R.id.ll_image_selection);
        pro_img = (ImageView) findViewById(R.id.pro_img);

        countryPbar = (ProgressBar) findViewById(R.id.countryPbar);
        country_spinner = (Spinner) findViewById(R.id.country_spinner);
        countryPbar.setVisibility(View.VISIBLE);
        country_spinner.setVisibility(View.GONE);

        txt_terms_conditions = (RobotoBold) findViewById(R.id.txt_terms_conditions);

        country_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                try {
                    country_2_code = objectsCountry.get(position).getString("country_2_code");
                    country_id = objectsCountry.get(position).getString("country_id");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        ll_image_selection.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RegistrationActivity.this, ImageTakerActivityCamera.class);
                startActivityForResult(i, 1);
            }
        });

        txt_terms_conditions.setText(Html.fromHtml("<u>Terms and Condition</u>"));
        txt_terms_conditions.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogTermsUse();
            }
        });

        findViewById(R.id.footer).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        findViewById(R.id.help_password).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
                        RegistrationActivity.this);
                alertDialogBuilder.setTitle("Password Requirements");
                alertDialogBuilder.setMessage(
                        "Please Ensure that Password should have at least 6 characters (Maximum 20) long and it contains at least one lowercase letter, one uppercase letter, one number and one special character.")
                        .setCancelable(false).setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                android.app.AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });

        findViewById(R.id.help_dob).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
                        RegistrationActivity.this);
                alertDialogBuilder.setTitle("Date of Birth");
                alertDialogBuilder
                        .setMessage("We require date of birth to verify that no minors are bidding on the jobs.")
                        .setCancelable(false).setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                android.app.AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });
        findViewById(R.id.help_license).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
                        RegistrationActivity.this);
                alertDialogBuilder.setTitle("License");
                alertDialogBuilder
                        .setMessage("Please select if you have any work licenses like electrician, plumber, etc...")
                        .setCancelable(false).setPositiveButton("ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
                android.app.AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });

        gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //Logger.showMessage("Geder : ", "" + checkedId);
                if (("" + checkedId).equalsIgnoreCase("2131558563")) {//female
                    genderData = "" + 2;
                } else {
                    genderData = "" + 1;
                }
            }
        });

        ll_license.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RegistrationActivity.this, LicenseActivity.class);
                startActivityForResult(i, 420);
            }
        });

        findViewById(R.id.loginBttn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                license_ = "";
                if (fstName.getText().toString().trim().equalsIgnoreCase("")) {
                    fstName.setError("Please enter name.");
                    fstName.requestFocus();
                } else {
                    if (email.getText().toString().trim().equalsIgnoreCase("")) {
                        email.setError("Please enter email.");
                        email.requestFocus();
                    } else {
                        if (android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim())
                                .matches()) {
                            if (email_confirm.getText().toString().trim().equalsIgnoreCase("")) {
                                email_confirm.setError("Please enter email again.");
                                email_confirm.requestFocus();
                            } else {
                                if (android.util.Patterns.EMAIL_ADDRESS
                                        .matcher(email_confirm.getText().toString().trim()).matches()) {
                                    if (email.getText().toString().trim()
                                            .equalsIgnoreCase(email_confirm.getText().toString().trim())) {
                                        if (!android.util.Patterns.PHONE.matcher(mobile.getText().toString().trim())
                                                .matches()) {
                                            mobile.setError("Please enter valid mobile number.");
                                            mobile.requestFocus();
                                        } else {
                                            //                                            if (password.getText().toString().trim().equalsIgnoreCase("")) {
                                            if (!isValidPassword(password.getText().toString().trim())) {
                                                password.setError(
                                                        "Please Ensure that Password should have at least 6 characters (Maximum 20) long and it contains at least one lowercase letter, one uppercase letter, one number and one special character.");
                                                password.requestFocus();
                                            } else {
                                                if (conformPassword.getText().toString().trim()
                                                        .equalsIgnoreCase("")) {
                                                    conformPassword.setError("Please enter password again.");
                                                    conformPassword.requestFocus();
                                                } else {
                                                    if (conformPassword.getText().toString().trim()
                                                            .equals(password.getText().toString().trim())) {
                                                        if (dateOfBirth.getText().toString().trim()
                                                                .equalsIgnoreCase("Birth date")) {
                                                            Snackbar.make(findViewById(android.R.id.content),
                                                                    "Please select date of birth",
                                                                    Snackbar.LENGTH_LONG)
                                                                    .setActionTextColor(Color.RED).show();
                                                        } else {
                                                            if (isValidDOB(
                                                                    dateOfBirth.getText().toString().trim())) {
                                                                if (country_2_code.equalsIgnoreCase("0")) {
                                                                    Snackbar.make(
                                                                            findViewById(android.R.id.content),
                                                                            "Select Country From List",
                                                                            Snackbar.LENGTH_LONG)
                                                                            .setActionTextColor(Color.RED).show();
                                                                } else {
                                                                    if (InstiworkApplication.getInstance()
                                                                            .getSelectedLicenseArray() != null) {
                                                                        for (int i = 0; i < InstiworkApplication
                                                                                .getInstance()
                                                                                .getSelectedLicenseArray()
                                                                                .size(); i++) {
                                                                            try {
                                                                                if (i == 0) {
                                                                                    license_ = license_
                                                                                            + InstiworkApplication
                                                                                                    .getInstance()
                                                                                                    .getSelectedLicenseArray()
                                                                                                    .get(i)
                                                                                                    .getString(
                                                                                                            "id");
                                                                                } else {
                                                                                    license_ = license_ + ","
                                                                                            + InstiworkApplication
                                                                                                    .getInstance()
                                                                                                    .getSelectedLicenseArray()
                                                                                                    .get(i)
                                                                                                    .getString(
                                                                                                            "id");
                                                                                }
                                                                            } catch (Exception e) {
                                                                                e.printStackTrace();
                                                                            }
                                                                        }
                                                                    }
                                                                    if (((CheckBox) findViewById(R.id.trmscondi))
                                                                            .isChecked()) {

                                                                        ll_image_selection.setEnabled(false);
                                                                        txt_terms_conditions.setEnabled(false);
                                                                        findViewById(R.id.footer).setEnabled(false);
                                                                        findViewById(R.id.help_password)
                                                                                .setEnabled(false);
                                                                        findViewById(R.id.help_dob)
                                                                                .setEnabled(false);
                                                                        findViewById(R.id.help_license)
                                                                                .setEnabled(false);

                                                                        ll_license.setEnabled(false);
                                                                        findViewById(R.id.loginBttn)
                                                                                .setEnabled(false);
                                                                        findViewById(R.id.fb_log).setEnabled(false);
                                                                        dateOfBirth.setEnabled(false);
                                                                        ll_image_selection.setClickable(false);
                                                                        txt_terms_conditions.setClickable(false);
                                                                        findViewById(R.id.footer)
                                                                                .setClickable(false);
                                                                        findViewById(R.id.help_password)
                                                                                .setClickable(false);
                                                                        findViewById(R.id.help_dob)
                                                                                .setClickable(false);
                                                                        findViewById(R.id.help_license)
                                                                                .setClickable(false);

                                                                        ll_license.setClickable(false);
                                                                        findViewById(R.id.loginBttn)
                                                                                .setClickable(false);
                                                                        findViewById(R.id.fb_log)
                                                                                .setClickable(false);
                                                                        dateOfBirth.setClickable(false);

                                                                        try {
                                                                            if (appSharedPref
                                                                                    .getString("GCM_TOKEN", "")
                                                                                    .equalsIgnoreCase("")) {
                                                                                String date[] = dateOfBirth
                                                                                        .getText().toString().trim()
                                                                                        .split("/");
                                                                                final String URL = InstiworkConstants.URL_DOMAIN
                                                                                        + "Signup_ios?name="
                                                                                        + URLEncoder.encode(
                                                                                                fstName.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&contact="
                                                                                        + URLEncoder.encode(
                                                                                                mobile.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&companyname="
                                                                                        + URLEncoder.encode(
                                                                                                lastname.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&email="
                                                                                        + URLEncoder.encode(
                                                                                                email.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&password="
                                                                                        + URLEncoder.encode(
                                                                                                password.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&gender=" + genderData
                                                                                        + "&year=" + date[2]
                                                                                        + "&month=" + date[0]
                                                                                        + "&date=" + date[1]
                                                                                        + "&license="
                                                                                        + URLEncoder.encode(
                                                                                                license_, "UTF-8")
                                                                                        + "&device_type=2" + "&lat="
                                                                                        + LOCATION_LATITUDE
                                                                                        + "&lng="
                                                                                        + LOCATION_LONGITUDE
                                                                                        + "&country2_code="
                                                                                        + country_2_code
                                                                                        + "&country_id="
                                                                                        + country_id
                                                                                        + "&device_token=";
                                                                                (new RegistrationGCM(URL))
                                                                                        .executeOnExecutor(
                                                                                                AsyncTask.THREAD_POOL_EXECUTOR);
                                                                            } else {
                                                                                gcmToken = appSharedPref
                                                                                        .getString("GCM_TOKEN", "");
                                                                                String date[] = dateOfBirth
                                                                                        .getText().toString().trim()
                                                                                        .split("/");
                                                                                final String URL = InstiworkConstants.URL_DOMAIN
                                                                                        + "Signup_ios?name="
                                                                                        + URLEncoder.encode(
                                                                                                fstName.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&contact="
                                                                                        + URLEncoder.encode(
                                                                                                mobile.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&companyname="
                                                                                        + URLEncoder.encode(
                                                                                                lastname.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&email="
                                                                                        + URLEncoder.encode(
                                                                                                email.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&password="
                                                                                        + URLEncoder.encode(
                                                                                                password.getText()
                                                                                                        .toString()
                                                                                                        .trim(),
                                                                                                "UTF-8")
                                                                                        + "&gender=" + genderData
                                                                                        + "&year=" + date[2]
                                                                                        + "&month=" + date[0]
                                                                                        + "&date=" + date[1]
                                                                                        + "&license=" + license_
                                                                                        + "&device_type=2&device_token="
                                                                                        + URLEncoder.encode(
                                                                                                gcmToken, "UTF-8")
                                                                                        + "&lat="
                                                                                        + LOCATION_LATITUDE
                                                                                        + "&lng="
                                                                                        + LOCATION_LONGITUDE
                                                                                        + "&country2_code="
                                                                                        + country_2_code
                                                                                        + "&country_id="
                                                                                        + country_id;
                                                                                //
                                                                                login_User(URL);
                                                                            }
                                                                        } catch (Exception e) {
                                                                            e.printStackTrace();
                                                                        }
                                                                    } else {
                                                                        Snackbar.make(
                                                                                findViewById(android.R.id.content),
                                                                                "Please agree to Terms And Conditions.",
                                                                                Snackbar.LENGTH_LONG)
                                                                                .setActionTextColor(Color.RED)
                                                                                .show();
                                                                    }
                                                                }
                                                            } else {
                                                                Snackbar.make(findViewById(android.R.id.content),
                                                                        "You are under 14 years old.",
                                                                        Snackbar.LENGTH_LONG)
                                                                        .setActionTextColor(Color.RED).show(); //soutrik
                                                            }
                                                        }
                                                    } else {
                                                        conformPassword.setError(
                                                                "Password amd confirm password should be same.");
                                                        conformPassword.requestFocus();
                                                    }
                                                }
                                            }
                                        }
                                    } else {
                                        email_confirm.setError("Email amd confirm email should be same.");
                                        email_confirm.requestFocus();
                                    }
                                } else {
                                    email_confirm.setError("Please enter valid email.");
                                    email_confirm.requestFocus();
                                }
                            }
                        } else {
                            email.setError("Please enter valid email.");
                            email.requestFocus();
                        }
                    }
                }
            }
        });

        findViewById(R.id.fb_log).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (appSharedPref.getString("GCM_TOKEN", "").equalsIgnoreCase("")) {
                    (new RegistrationGCMFB()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                } else {
                    gcmToken = appSharedPref.getString("GCM_TOKEN", "");
                    LoginManager.getInstance().logInWithReadPermissions(RegistrationActivity.this,
                            Arrays.asList("public_profile", "email"));
                }
            }
        });

        //---------Facebook
        LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                fbAccessToken = loginResult.getAccessToken().getToken();
                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                //                                        Log.i("FBRESULT", object.toString());
                                pDialogOut.setMessage("Authenticate Facebook User.");
                                pDialogOut.show();
                                try {
                                    final String URL = InstiworkConstants.URL_DOMAIN
                                            + "Login_ios/checkfacebooksignup?facebook_id=" + object.getString("id")
                                            + "&device_token=" + URLEncoder.encode(gcmToken, "UTF-8")
                                            + "&device_type=2";
                                    FB_ChkUser(URL, object);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,birthday,first_name,last_name,gender");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                // App code
                pDialogOut.dismiss();
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                pDialogOut.dismiss();
                if (exception instanceof FacebookAuthorizationException) {
                    if (AccessToken.getCurrentAccessToken() != null) {
                        LoginManager.getInstance().logOut();
                        LoginManager.getInstance().logInWithReadPermissions(RegistrationActivity.this,
                                Arrays.asList("public_profile", "email"));
                    } else {
                        //                                Toast.makeText(RegistrationActivity.this, "Facebook Exception : " + exception.toString(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //                            Toast.makeText(RegistrationActivity.this, "Facebook Exception : " + exception.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        dateOfBirth.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {//soutrik

                Calendar today = Calendar.getInstance();

                View dialoglayout = LayoutInflater.from(getApplicationContext())
                        .inflate(R.layout.dialog_date_picker, null);
                final DatePicker dPicker = (DatePicker) dialoglayout.findViewById(R.id.date_picker);

                dPicker.setMaxDate(today.getTimeInMillis()); // set DatePicker MAX Date
                today.set(dPicker.getYear(), dPicker.getMonth() + 1, dPicker.getDayOfMonth());
                today.add(Calendar.YEAR, -14);
                dPicker.updateDate(today.get(Calendar.YEAR), today.get(Calendar.MONTH) - 1,
                        today.get(Calendar.DATE));

                AlertDialog.Builder builder = new AlertDialog.Builder(RegistrationActivity.this);
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        try {
                            SimpleDateFormat changeFormat = new SimpleDateFormat("MM/dd/yyyy");
                            Calendar newDate = Calendar.getInstance();
                            newDate.set(dPicker.getYear(), dPicker.getMonth(), dPicker.getDayOfMonth());
                            dateOfBirth.setText(changeFormat.format(newDate.getTime()));
                            Logger.showMessage("DOBBBBB : ", changeFormat.format(newDate.getTime()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        dateOfBirth.setText("Birth date");
                    }
                });
                builder.setView(dialoglayout);
                builder.show();
            }
        });

        //        getCountryList();
        buildGoogleApiClient();
        if (gMapOption == null) {
            gMapOption = new GoogleMapOptions();
            gMapOption.ambientEnabled(true);
            gMapOption.compassEnabled(true);
        }
    }

    public boolean isValidDOB(String dob) {
        try {
            Calendar compareDate = Calendar.getInstance();
            compareDate.add(compareDate.YEAR, -14);

            SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
            Date strDate = sdf.parse(dob);
            Date cDate = sdf.parse(sdf.format(compareDate.getTime()));
            if (cDate.after(strDate)) {
                return true;
            } else if (cDate.equals(strDate)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            Logger.showMessage(TAG, " DOB Exception : " + e.toString());
            return false;
        }
    }

    public void getCountryList() {

        final String URL = InstiworkConstants.URL_DOMAIN + "Councurr_control";

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Logger.showMessage(TAG, URL);
                        Logger.showMessage(TAG, response.toString());
                        countryPbar.setVisibility(View.GONE);
                        objectsCountry = new LinkedList<JSONObject>();
                        try {
                            JSONObject makeJSONObject = new JSONObject();

                            makeJSONObject.put("country_id", "0");
                            makeJSONObject.put("country_name", "Select Country From List");
                            makeJSONObject.put("country_2_code", "0");
                            makeJSONObject.put("currency_name", "");
                            makeJSONObject.put("currency_code", "");

                            objectsCountry.add(makeJSONObject);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        country_spinner.setVisibility(View.VISIBLE);
                        try {
                            JSONArray jsonArray = response.getJSONArray("response");
                            for (int i = 0; i < jsonArray.length(); i++) {
                                objectsCountry.add(jsonArray.getJSONObject(i));
                            }
                            country_spinner.setAdapter(
                                    new CountrySpinnerAdapter(RegistrationActivity.this, objectsCountry));

                            try {
                                for (int s = 0; s < objectsCountry.size(); s++) {
                                    if (objectsCountry.get(s).getString("country_name")
                                            .equalsIgnoreCase(currentCountry)) {
                                        Logger.showMessage(TAG, "MyCheck: " + "IF");
                                        country_spinner.setSelection(s);
                                        break;
                                    } else {
                                        Logger.showMessage(TAG, "MyCheck: " + "ELSE");
                                        country_spinner.setSelection(0);
                                    }
                                }
                            } catch (Exception e) {
                                //                                e.printStackTrace();
                                country_spinner.setSelection(0);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Logger.showMessage(TAG, "Error: " + error.getMessage());
                        countryPbar.setVisibility(View.GONE);
                        if (error instanceof NoConnectionError) {
                            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                    RegistrationActivity.this);
                            builder.setTitle("Instiwork");
                            builder.setMessage("You do not have internet connection!");
                            builder.setPositiveButton("retry", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                    countryPbar.setVisibility(View.VISIBLE);
                                    country_spinner.setVisibility(View.GONE);
                                    getCountryList();
                                }
                            });
                            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
                            builder.setCancelable(false);
                            builder.show();
                        } else {
                            try {
                                String json = null;
                                NetworkResponse response = error.networkResponse;
                                if (response != null && response.data != null) {
                                    json = new String(response.data);
                                    json = trimMessage(json, "message");
                                    if (json != null)
                                        //                                displayMessage(json);
                                        displayMessage(json + " Error Code : " + response.statusCode);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        InstiworkApplication.getInstance().addToRequestQueue(jsonObjReq);
    }

    public void FB_ChkUser(final String URL, final JSONObject jObject) {

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Logger.showMessage(TAG, URL);
                        Logger.showMessage(TAG, response.toString());

                        ll_image_selection.setEnabled(true);
                        txt_terms_conditions.setEnabled(true);
                        findViewById(R.id.footer).setEnabled(true);
                        findViewById(R.id.help_password).setEnabled(true);
                        findViewById(R.id.help_dob).setEnabled(true);
                        findViewById(R.id.help_license).setEnabled(true);

                        ll_license.setEnabled(true);
                        findViewById(R.id.loginBttn).setEnabled(true);
                        findViewById(R.id.fb_log).setEnabled(true);
                        dateOfBirth.setEnabled(true);
                        ll_image_selection.setClickable(true);
                        txt_terms_conditions.setClickable(true);
                        findViewById(R.id.footer).setClickable(true);
                        findViewById(R.id.help_password).setClickable(true);
                        findViewById(R.id.help_dob).setClickable(true);
                        findViewById(R.id.help_license).setClickable(true);

                        ll_license.setClickable(true);
                        findViewById(R.id.loginBttn).setClickable(true);
                        findViewById(R.id.fb_log).setClickable(true);
                        dateOfBirth.setClickable(true);

                        try {
                            if (response.getJSONObject("response").getString("status")
                                    .equalsIgnoreCase("Success")) {

                                LoginManager.getInstance().logOut();

                                pDialogOut.hide();
                                InstiworkApplication.getInstance()
                                        .setUSER_ID(response.getJSONObject("response").getString("userid"));
                                InstiworkApplication.getInstance()
                                        .setUSER_NAME(response.getJSONObject("response").getString("Company_name"));
                                InstiworkApplication.getInstance()
                                        .setUSER_EMAIL(response.getJSONObject("response").getString("email"));
                                //                                InstiworkApplication.getInstance().setUSER_IMG("https://graph.facebook.com/" + jObject.getString("id") + "/picture?type=large");
                                InstiworkApplication.getInstance()
                                        .setMOBILE_NO(response.getJSONObject("response").getString("email"));
                                InstiworkApplication.getInstance().setUSER_IMG(
                                        (response.getJSONObject("response").getString("profileimage")));

                                try {
                                    InstiworkApplication.getInstance().setPush_status(
                                            response.getJSONObject("response").getString("push_status"));
                                    InstiworkApplication.getInstance().setEmail_status(
                                            response.getJSONObject("response").getString("email_status"));
                                    InstiworkApplication.getInstance().setText_status(
                                            response.getJSONObject("response").getString("text_status"));
                                    InstiworkApplication.getInstance().setCountryid(
                                            response.getJSONObject("response").getString("country_id"));
                                    InstiworkApplication.getInstance().setCurrency_id(
                                            response.getJSONObject("response").getString("currency_id"));
                                    InstiworkApplication.getInstance().setCountry_name(
                                            response.getJSONObject("response").getString("country_name"));
                                    InstiworkApplication.getInstance().setCountry_3_code(
                                            response.getJSONObject("response").getString("country_3_code"));
                                    InstiworkApplication.getInstance().setCountry_2_code(
                                            response.getJSONObject("response").getString("country_2_code"));
                                    InstiworkApplication.getInstance().setCurrency_code(
                                            response.getJSONObject("response").getString("currency_code"));
                                    InstiworkApplication.getInstance().setCurrency_name(
                                            response.getJSONObject("response").getString("currency_name"));
                                    InstiworkApplication.getInstance().setMember_since(
                                            response.getJSONObject("response").getString("member_since"));

                                } catch (Exception e) {
                                    Logger.showMessage(TAG, "Extra Paremeter : " + e.toString());
                                }

                                if (response.getJSONObject("response").getString("contact").equalsIgnoreCase("0")) {
                                    InstiworkApplication.getInstance().setMOBILE_NO("");
                                } else {
                                    InstiworkApplication.getInstance()
                                            .setMOBILE_NO(response.getJSONObject("response").getString("contact"));
                                }
                                InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                        response.getJSONObject("response").getString("distance_user"));
                                InstiworkApplication.getInstance()
                                        .setUnit_user(response.getJSONObject("response").getString("unit_user"));
                                try {
                                    licenseLinkedList = new LinkedList<JSONObject>();
                                    if (response.getJSONObject("response").getJSONArray("license").length() > 0) {
                                        for (int i = 0; i < response.getJSONObject("response")
                                                .getJSONArray("license").length(); i++) {
                                            licenseLinkedList.add(response.getJSONObject("response")
                                                    .getJSONArray("license").getJSONObject(i));
                                        }
                                        InstiworkApplication.getInstance().setLicenseArray(licenseLinkedList);
                                    } else {
                                        InstiworkApplication.getInstance().setLicenseArray(null);
                                    }
                                } catch (Exception e) {
                                    InstiworkApplication.getInstance().setLicenseArray(null);
                                    Logger.showMessage(TAG, "license Exception" + e.toString());
                                }

                                SharedPreferences.Editor edit = appSharedPref.edit();
                                edit.putString("USER_ID", response.getJSONObject("response").getString("userid"));
                                try {
                                    edit.putString("CURRENCY_ID",
                                            response.getJSONObject("response").getString("currency_id"));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                edit.commit();

                                try {
                                    Map<String, Object> params = new HashMap<>();
                                    params.put("action", "facebook_login");
                                    params.put("action_user_id", InstiworkApplication.getInstance().getUSER_ID());
                                    params.put("action_user_name",
                                            InstiworkApplication.getInstance().getUSER_NAME());
                                    AdWordsRemarketingReporter.reportWithConversionId(getApplicationContext(),
                                            getResources().getString(R.string.conversion_id), params);
                                    params.put("action_device", "android");
                                } catch (Exception e) {
                                    Logger.showMessage(TAG, "AdWords : " + e.toString());
                                }

                                Intent i = new Intent(getApplicationContext(), LandingActivity.class);
                                Toast.makeText(RegistrationActivity.this, "Registered successfully",
                                        Toast.LENGTH_SHORT).show();
                                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                startActivity(i);
                                finish();

                            } else {
                                Toast.makeText(RegistrationActivity.this, "New User Register First.",
                                        Toast.LENGTH_SHORT).show();

                                Intent fbIntent = new Intent(RegistrationActivity.this,
                                        RegistrationFacebookActivity.class);
                                fbIntent.putExtra("FromIntent", "RegistrationActivity");
                                fbIntent.putExtra("FB_ID", "" + jObject.getString("id"));
                                fbIntent.putExtra("FB_ACCESS_TOKEN", "" + fbAccessToken);
                                fbIntent.putExtra("FB_DEVICE_TOKEN", "" + gcmToken);
                                try {
                                    fbIntent.putExtra("FB_NAME", "" + jObject.getString("first_name") + " "
                                            + jObject.getString("last_name"));
                                } catch (Exception ee) {
                                    fbIntent.putExtra("FB_NAME", "");
                                }
                                try {
                                    fbIntent.putExtra("FB_EMAIL", "" + jObject.getString("email"));
                                } catch (Exception ee) {
                                    fbIntent.putExtra("FB_EMAIL", "");
                                }
                                try {
                                    fbIntent.putExtra("FB_BIRTHDAY", "" + jObject.getString("birthday"));
                                } catch (Exception ee) {
                                    fbIntent.putExtra("FB_BIRTHDAY", "");
                                }
                                try {
                                    fbIntent.putExtra("FB_GENDER", "" + jObject.getString("gender"));
                                } catch (Exception ee) {
                                    fbIntent.putExtra("FB_GENDER", "");
                                }
                                try {
                                    fbIntent.putExtra("FB_IMG", "" + "https://graph.facebook.com/"
                                            + jObject.getString("id") + "/picture?type=large");
                                } catch (Exception ee) {
                                    fbIntent.putExtra("FB_IMG", "");
                                }
                                startActivity(fbIntent);
                                finish();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Logger.showMessage(TAG, "Error: " + error.getMessage());
                        pDialogOut.hide();

                        ll_image_selection.setEnabled(true);
                        txt_terms_conditions.setEnabled(true);
                        findViewById(R.id.footer).setEnabled(true);
                        findViewById(R.id.help_password).setEnabled(true);
                        findViewById(R.id.help_dob).setEnabled(true);
                        findViewById(R.id.help_license).setEnabled(true);

                        ll_license.setEnabled(true);
                        findViewById(R.id.loginBttn).setEnabled(true);
                        findViewById(R.id.fb_log).setEnabled(true);
                        dateOfBirth.setEnabled(true);
                        ll_image_selection.setClickable(true);
                        txt_terms_conditions.setClickable(true);
                        findViewById(R.id.footer).setClickable(true);
                        findViewById(R.id.help_password).setClickable(true);
                        findViewById(R.id.help_dob).setClickable(true);
                        findViewById(R.id.help_license).setClickable(true);

                        ll_license.setClickable(true);
                        findViewById(R.id.loginBttn).setClickable(true);
                        findViewById(R.id.fb_log).setClickable(true);
                        dateOfBirth.setClickable(true);

                        if (error instanceof NoConnectionError) {
                            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                    RegistrationActivity.this);
                            builder.setTitle("Instiwork");
                            builder.setMessage("You do not have internet connection!");
                            builder.setPositiveButton("retry", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                    pDialogOut.show();

                                    ll_image_selection.setEnabled(false);
                                    txt_terms_conditions.setEnabled(false);
                                    findViewById(R.id.footer).setEnabled(false);
                                    findViewById(R.id.help_password).setEnabled(false);
                                    findViewById(R.id.help_dob).setEnabled(false);
                                    findViewById(R.id.help_license).setEnabled(false);

                                    ll_license.setEnabled(false);
                                    findViewById(R.id.loginBttn).setEnabled(false);
                                    findViewById(R.id.fb_log).setEnabled(false);
                                    dateOfBirth.setEnabled(false);
                                    ll_image_selection.setClickable(false);
                                    txt_terms_conditions.setClickable(false);
                                    findViewById(R.id.footer).setClickable(false);
                                    findViewById(R.id.help_password).setClickable(false);
                                    findViewById(R.id.help_dob).setClickable(false);
                                    findViewById(R.id.help_license).setClickable(false);

                                    ll_license.setClickable(false);
                                    findViewById(R.id.loginBttn).setClickable(false);
                                    findViewById(R.id.fb_log).setClickable(false);
                                    dateOfBirth.setClickable(false);

                                    FB_ChkUser(URL, jObject);
                                }
                            });
                            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
                            builder.setCancelable(false);
                            builder.show();
                        } else {
                            try {
                                String json = null;
                                NetworkResponse response = error.networkResponse;
                                if (response != null && response.data != null) {
                                    json = new String(response.data);
                                    json = trimMessage(json, "message");
                                    if (json != null)
                                        //                                displayMessage(json);
                                        displayMessage(json + " Error Code : " + response.statusCode);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        InstiworkApplication.getInstance().addToRequestQueue(jsonObjReq);
    }

    public class RegistrationGCMFB extends AsyncTask<Void, Void, Void> {

        ProgressDialog pDialog = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(RegistrationActivity.this);
            pDialog.setMessage("Registering Instiwork to Google");
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.dismiss();
            pDialogOut.setMessage("Authenticate Facebook User.");
            pDialogOut.show();
            LoginManager.getInstance().logInWithReadPermissions(RegistrationActivity.this,
                    Arrays.asList("public_profile", "email"));
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                InstanceID instanceID = InstanceID.getInstance(RegistrationActivity.this);
                gcmToken = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                SharedPreferences.Editor edit = appSharedPref.edit();
                edit.putString("RegistrationActivity", gcmToken);
                edit.commit();
                Logger.showMessage("RegistrationActivity", gcmToken);
            } catch (IOException e) {
                e.printStackTrace();
                Logger.showMessage("RegistrationActivity", e.toString());
            }
            return null;
        }
    }

    public class RegistrationGCM extends AsyncTask<Void, Void, Void> {

        ProgressDialog pDialog = null;
        String URL = "";

        public RegistrationGCM(final String URL) {
            this.URL = URL;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(RegistrationActivity.this);
            pDialog.setMessage("Registering Instiwork to Google");
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.dismiss();
            try {
                URL = URL + URLEncoder.encode(gcmToken, "UTF-8");
                Logger.showMessage("RegistrationActivity", URL);
                login_User(URL);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                InstanceID instanceID = InstanceID.getInstance(RegistrationActivity.this);
                gcmToken = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
                        GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                SharedPreferences.Editor edit = appSharedPref.edit();
                edit.putString("GCM_TOKEN", gcmToken);
                edit.commit();
                Logger.showMessage("RegistrationActivity", gcmToken);
            } catch (IOException e) {
                e.printStackTrace();
                Logger.showMessage("RegistrationActivity", e.toString());
            }
            return null;
        }
    }

    public void login_User(final String URL) {

        if (pDialogOut != null) {
            pDialogOut.show();
        }

        Logger.showMessage(TAG, "OutSide login_User" + URL);
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, URL, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Logger.showMessage(TAG, "Inside login_User" + URL);
                        Logger.showMessage(TAG, response.toString());
                        Logger.showMessage(TAG, imgPath);

                        ll_image_selection.setEnabled(true);
                        txt_terms_conditions.setEnabled(true);
                        findViewById(R.id.footer).setEnabled(true);
                        findViewById(R.id.help_password).setEnabled(true);
                        findViewById(R.id.help_dob).setEnabled(true);
                        findViewById(R.id.help_license).setEnabled(true);

                        ll_license.setEnabled(true);
                        findViewById(R.id.loginBttn).setEnabled(true);
                        findViewById(R.id.fb_log).setEnabled(true);
                        dateOfBirth.setEnabled(true);
                        ll_image_selection.setClickable(true);
                        txt_terms_conditions.setClickable(true);
                        findViewById(R.id.footer).setClickable(true);
                        findViewById(R.id.help_password).setClickable(true);
                        findViewById(R.id.help_dob).setClickable(true);
                        findViewById(R.id.help_license).setClickable(true);

                        ll_license.setClickable(true);
                        findViewById(R.id.loginBttn).setClickable(true);
                        findViewById(R.id.fb_log).setClickable(true);
                        dateOfBirth.setClickable(true);

                        try {
                            InstiworkApplication.getInstance().setSelectedLicenseArray(null);
                            if (response.getString("status").equalsIgnoreCase("Success")) {

                                SharedPreferences.Editor edit = appSharedPref.edit();
                                edit.putString("USER_ID", response.getJSONObject("details").getString("userid"));
                                try {
                                    edit.putString("CURRENCY_ID",
                                            response.getJSONObject("details").getString("currency_id"));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                edit.commit();

                                InstiworkApplication.getInstance()
                                        .setUSER_ID(response.getJSONObject("details").getString("userid"));
                                InstiworkApplication.getInstance()
                                        .setUSER_NAME(response.getJSONObject("details").getString("name"));
                                InstiworkApplication.getInstance().setCOMPANY_NAME(
                                        response.getJSONObject("details").getString("companyname"));
                                InstiworkApplication.getInstance()
                                        .setUSER_EMAIL(response.getJSONObject("details").getString("email"));
                                InstiworkApplication.getInstance()
                                        .setMOBILE_NO(response.getJSONObject("details").getString("contact"));
                                try {
                                    InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                            response.getJSONObject("details").getString("distance"));
                                    InstiworkApplication.getInstance()
                                            .setUnit_user(response.getJSONObject("details").getString("unit"));
                                } catch (Exception e) {
                                    try {
                                        InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                                response.getJSONObject("details").getString("distance_user"));
                                        InstiworkApplication.getInstance().setUnit_user(
                                                response.getJSONObject("details").getString("unit_user"));
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                    }
                                }

                                try {
                                    InstiworkApplication.getInstance().setPush_status(
                                            response.getJSONObject("details").getString("push_status"));
                                    InstiworkApplication.getInstance().setEmail_status(
                                            response.getJSONObject("details").getString("email_status"));
                                    InstiworkApplication.getInstance().setText_status(
                                            response.getJSONObject("details").getString("text_status"));
                                    InstiworkApplication.getInstance().setCountryid(
                                            response.getJSONObject("details").getString("country_id"));
                                    InstiworkApplication.getInstance().setCurrency_id(
                                            response.getJSONObject("details").getString("currency_id"));
                                    InstiworkApplication.getInstance().setCountry_name(
                                            response.getJSONObject("details").getString("country_name"));
                                    InstiworkApplication.getInstance().setCountry_3_code(
                                            response.getJSONObject("details").getString("country_3_code"));
                                    InstiworkApplication.getInstance().setCountry_2_code(
                                            response.getJSONObject("details").getString("country_2_code"));
                                    InstiworkApplication.getInstance().setCurrency_code(
                                            response.getJSONObject("details").getString("currency_code"));
                                    InstiworkApplication.getInstance().setCurrency_name(
                                            response.getJSONObject("details").getString("currency_name"));
                                    InstiworkApplication.getInstance().setMember_since(
                                            response.getJSONObject("details").getString("member_since"));

                                } catch (Exception e) {
                                    Logger.showMessage(TAG, "Extra Paremeter : " + e.toString());
                                }

                                try {
                                    licenseLinkedList = new LinkedList<JSONObject>();
                                    if (response.getJSONObject("details").getJSONArray("license").length() > 0) {
                                        for (int i = 0; i < response.getJSONObject("details")
                                                .getJSONArray("license").length(); i++) {
                                            licenseLinkedList.add(response.getJSONObject("details")
                                                    .getJSONArray("license").getJSONObject(i));
                                        }
                                        InstiworkApplication.getInstance().setLicenseArray(licenseLinkedList);
                                    } else {
                                        InstiworkApplication.getInstance().setLicenseArray(null);
                                    }
                                } catch (Exception e) {
                                    InstiworkApplication.getInstance().setLicenseArray(null);
                                    Logger.showMessage(TAG, "license Exception" + e.toString());
                                }

                                try {
                                    Map<String, Object> params = new HashMap<>();
                                    params.put("action", "registration");
                                    params.put("action_user_id", InstiworkApplication.getInstance().getUSER_ID());
                                    params.put("action_user_name",
                                            InstiworkApplication.getInstance().getUSER_NAME());
                                    params.put("action_device", "android");
                                    AdWordsRemarketingReporter.reportWithConversionId(getApplicationContext(),
                                            getResources().getString(R.string.conversion_id), params);
                                } catch (Exception e) {
                                    Logger.showMessage(TAG, "AdWords : " + e.toString());
                                }

                                if (imgPath.equalsIgnoreCase("")) {
                                    if (pDialogOut != null) {
                                        pDialogOut.dismiss();
                                    }
                                    Toast.makeText(RegistrationActivity.this, "Registered successfully",
                                            Toast.LENGTH_SHORT).show();

                                    InstiworkApplication.getInstance()
                                            .setUSER_IMG("" + R.drawable.placeholder_circuler);
                                    Intent i = new Intent(getApplicationContext(), LandingActivity.class);
                                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                    startActivity(i);
                                    finish();
                                } else {
                                    if (pDialogOut != null) {
                                        pDialogOut.show();
                                    }
                                    String imgUploadUrl = InstiworkConstants.URL_DOMAIN
                                            + "Signup_ios/add_user_image?user_id="
                                            + response.getJSONObject("details").getString("userid");
                                    (new UpdateAccountDetailsWithImage(imgPath, imgUploadUrl))
                                            .executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
                                }
                            } else {
                                pDialogOut.dismiss();

                                try {
                                    displayMessage(response.getString("details"));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    try {
                                        displayMessage(response.getString("message"));
                                    } catch (Exception ee) {
                                        ee.printStackTrace();
                                    }
                                }

                                //Toast.makeText(RegistrationActivity.this, response.getString("message"), Toast.LENGTH_SHORT).show();
                                //                                Snackbar.make(findViewById(android.R.id.content), response.getString("details"), Snackbar.LENGTH_LONG)
                                //                                        .setActionTextColor(Color.RED)
                                //                                        .show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Logger.showMessage(TAG, "Vollllllllll Error: " + error.getMessage());
                        pDialogOut.hide();

                        ll_image_selection.setEnabled(true);
                        txt_terms_conditions.setEnabled(true);
                        findViewById(R.id.footer).setEnabled(true);
                        findViewById(R.id.help_password).setEnabled(true);
                        findViewById(R.id.help_dob).setEnabled(true);
                        findViewById(R.id.help_license).setEnabled(true);

                        ll_license.setEnabled(true);
                        findViewById(R.id.loginBttn).setEnabled(true);
                        findViewById(R.id.fb_log).setEnabled(true);
                        dateOfBirth.setEnabled(true);
                        ll_image_selection.setClickable(true);
                        txt_terms_conditions.setClickable(true);
                        findViewById(R.id.footer).setClickable(true);
                        findViewById(R.id.help_password).setClickable(true);
                        findViewById(R.id.help_dob).setClickable(true);
                        findViewById(R.id.help_license).setClickable(true);

                        ll_license.setClickable(true);
                        findViewById(R.id.loginBttn).setClickable(true);
                        findViewById(R.id.fb_log).setClickable(true);
                        dateOfBirth.setClickable(true);

                        if (error instanceof NoConnectionError) {
                            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                    RegistrationActivity.this);
                            builder.setTitle("Instiwork");
                            builder.setMessage("You do not have internet connection!");
                            builder.setPositiveButton("retry", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();

                                    pDialogOut.show();

                                    ll_image_selection.setEnabled(false);
                                    txt_terms_conditions.setEnabled(false);
                                    findViewById(R.id.footer).setEnabled(false);
                                    findViewById(R.id.help_password).setEnabled(false);
                                    findViewById(R.id.help_dob).setEnabled(false);
                                    findViewById(R.id.help_license).setEnabled(false);

                                    ll_license.setEnabled(false);
                                    findViewById(R.id.loginBttn).setEnabled(false);
                                    findViewById(R.id.fb_log).setEnabled(false);
                                    dateOfBirth.setEnabled(false);
                                    ll_image_selection.setClickable(false);
                                    txt_terms_conditions.setClickable(false);
                                    findViewById(R.id.footer).setClickable(false);
                                    findViewById(R.id.help_password).setClickable(false);
                                    findViewById(R.id.help_dob).setClickable(false);
                                    findViewById(R.id.help_license).setClickable(false);

                                    ll_license.setClickable(false);
                                    findViewById(R.id.loginBttn).setClickable(false);
                                    findViewById(R.id.fb_log).setClickable(false);
                                    dateOfBirth.setClickable(false);

                                    login_User(URL);
                                }
                            });
                            builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.dismiss();
                                }
                            });
                            builder.setCancelable(false);
                            builder.show();
                        } else {
                            String json = null;
                            NetworkResponse response = error.networkResponse;
                            if (response != null && response.data != null) {
                                json = new String(response.data);
                                json = trimMessage(json, "message");
                                if (json != null)
                                    //                            displayMessage(json);
                                    displayMessage(json + " Error Code : " + response.statusCode);
                            }
                        }
                    }
                });
        jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        InstiworkApplication.getInstance().addToRequestQueue(jsonObjReq);
    }

    //================Profile image upload.

    public class UpdateAccountDetailsWithImage extends AsyncTask<Void, Void, Void> {

        String imgPath = "", regProfileUrl = "", exception = "", imageResponse = "";
        ImageCompress compress;

        public UpdateAccountDetailsWithImage(final String imgPath, final String regProfileUrl) {
            super();
            this.imgPath = imgPath;
            this.regProfileUrl = regProfileUrl;
            compress = new ImageCompress(getApplicationContext());
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
                OkHttpClient client = new OkHttpClient();
                Logger.showMessage(TAG, "Image upload file : " + imgPath);
                MultipartBody.Builder mBilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
                File file = new File(compress.compressImage(imgPath));
                Logger.showMessage(TAG, "Image upload compression : " + compress.compressImage(imgPath).toString());
                mBilder.addFormDataPart("user_image", file.getName().toString(),
                        RequestBody.create(MediaType.parse("image/*"), file));
                MultipartBody requestBody = mBilder.build();
                okhttp3.Request request = new okhttp3.Request.Builder().url(regProfileUrl).post(requestBody)
                        .build();
                okhttp3.Response response = client.newCall(request).execute();
                result = response.body().string();
                Logger.showMessage(TAG, "Image upload result : " + result);
                status = (new JSONObject(result)).getString("status");
                message = (new JSONObject(result)).getString("message");
                imageResponse = (new JSONObject(result)).getString("image");
            } catch (Exception ex) {
                exception = ex.toString();
                Logger.showMessage(TAG, "Image upload Exception : " + ex.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialogOut.hide();

            ll_image_selection.setEnabled(true);
            txt_terms_conditions.setEnabled(true);
            findViewById(R.id.footer).setEnabled(true);
            findViewById(R.id.help_password).setEnabled(true);
            findViewById(R.id.help_dob).setEnabled(true);
            findViewById(R.id.help_license).setEnabled(true);

            ll_license.setEnabled(true);
            findViewById(R.id.loginBttn).setEnabled(true);
            findViewById(R.id.fb_log).setEnabled(true);
            dateOfBirth.setEnabled(true);
            ll_image_selection.setClickable(true);
            txt_terms_conditions.setClickable(true);
            findViewById(R.id.footer).setClickable(true);
            findViewById(R.id.help_password).setClickable(true);
            findViewById(R.id.help_dob).setClickable(true);
            findViewById(R.id.help_license).setClickable(true);

            ll_license.setClickable(true);
            findViewById(R.id.loginBttn).setClickable(true);
            findViewById(R.id.fb_log).setClickable(true);
            dateOfBirth.setClickable(true);

            if (exception.equalsIgnoreCase("")) {
                if (status.equalsIgnoreCase("Success")) {
                    Toast.makeText(RegistrationActivity.this, "Registered successfully", Toast.LENGTH_SHORT).show();
                    InstiworkApplication.getInstance().setUSER_IMG(imageResponse);
                    Intent i = new Intent(getApplicationContext(), LandingActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(i);
                    finish();
                } else {

                    //=============Added by Saikat, 30th,April,2016
                    //=========If any cases unable to upload user images, It will move to next page with an error message that unable to upload images.
                    //------User can upload images later.
                    //====Error Was : Registration successfully, but unable to upload image, so it's showing error message. It's showing registration failed. On that case
                    //by next time we can't use that email id.

                    Toast.makeText(RegistrationActivity.this,
                            "Registered successfully. Unable to upload profile images.", Toast.LENGTH_SHORT).show();
                    InstiworkApplication.getInstance().setUSER_IMG("" + R.drawable.placeholder_circuler);
                    Intent i = new Intent(getApplicationContext(), LandingActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(i);
                    finish();

                    //                    Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG)
                    //                            .setActionTextColor(Color.RED)
                    //                            .show();

                    Toast.makeText(RegistrationActivity.this, message, Toast.LENGTH_SHORT).show();
                }
            } else {

                //=============Added by Saikat, 30th,April,2016
                //=========If any cases unable to upload user images, It will move to next page with an error message that unable to upload images.
                //------User can upload images later.
                //====Error Was : Registration successfully, but unable to upload image, so it's showing error message. It's showing registration failed. On that case
                //by next time we can't use that email id.

                Toast.makeText(RegistrationActivity.this,
                        "Registered successfully. Unable to upload profile images.", Toast.LENGTH_SHORT).show();
                InstiworkApplication.getInstance().setUSER_IMG("" + R.drawable.placeholder_circuler);
                Intent i = new Intent(getApplicationContext(), LandingActivity.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(i);
                finish();
            }
        }
    }

    public void clickItem() {
        Intent i = new Intent(RegistrationActivity.this, LicenseActivity.class);
        startActivityForResult(i, 420);
    }

    public void removeData(final JSONObject jObj_) {
        try {
            if (InstiworkApplication.getInstance().getSelectedLicenseArray().size() > 0) {
                selecteddata.smoothScrollToPosition(licenseHorizontalAdapter.getItemPosition(jObj_));
                licenseHorizontalAdapter.removeData(jObj_);
                for (int i = 0; i < InstiworkApplication.getInstance().getSelectedLicenseArray().size(); i++) {
                    try {
                        if (InstiworkApplication.getInstance().getSelectedLicenseArray().get(i).getString("id")
                                .equalsIgnoreCase(jObj_.getString("id"))) {
                            InstiworkApplication.getInstance().getSelectedLicenseArray().remove(jObj_);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (InstiworkApplication.getInstance().getSelectedLicenseArray().size() <= 0) {
                    selecteddata.setVisibility(View.GONE);
                    license.setVisibility(View.VISIBLE);
                }
            } else {
            }
        } catch (Exception e) {
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 420 && data != null) {
            if (InstiworkApplication.getInstance().getSelectedLicenseArray() != null) {
                selecteddata.setVisibility(View.VISIBLE);
                license.setVisibility(View.VISIBLE);
                try {
                    licenseHorizontalAdapter = new LicenseHorizontalAdapter(RegistrationActivity.this,
                            InstiworkApplication.getInstance().getSelectedLicenseArray());
                    selecteddata = (RecyclerView) findViewById(R.id.selecteddat);
                    selecteddata.setItemAnimator(new DefaultItemAnimator());
                    selecteddata.setAdapter(licenseHorizontalAdapter);
                    selecteddata.setLayoutManager(new LinearLayoutManager(getApplicationContext(),
                            LinearLayoutManager.HORIZONTAL, false));
                } catch (Exception e) {
                    selecteddata.setVisibility(View.GONE);
                    license.setVisibility(View.VISIBLE);
                    Logger.showMessage(TAG, "License : " + e.toString());
                }
            } else {
                selecteddata.setVisibility(View.GONE);
                license.setVisibility(View.VISIBLE);
            }
        } else if (resultCode == 1 && data != null) {
            try {
                imgPath = data.getStringExtra("data");
                if (!imgPath.equalsIgnoreCase("")) {
                    Glide.with(RegistrationActivity.this).load("file://" + data.getStringExtra("data"))
                            //                        .transform(new CornerMoldTransformation(24, 0, CornerMoldTransformation.CornerType.ALL))
                            //                            .fitCenter()
                            //                        .centerCrop()
                            .placeholder(R.mipmap.ic_launcher).into(pro_img);
                }
                Logger.showMessage(TAG, "Image Taker Exception " + imgPath);
            } catch (Exception e) {
                Logger.showMessage(TAG, "Image Taker Exception " + imgPath + "  \n" + e.toString());
            }
        }
    }

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            PermissionUtils.requestPermission(this, MY_PERMISSIONS_REQUEST_READ,
                    android.Manifest.permission.ACCESS_FINE_LOCATION, false);
        } else {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mLastLocation != null) {
                LOCATION_LATITUDE = "" + mLastLocation.getLatitude();
                LOCATION_LONGITUDE = "" + mLastLocation.getLongitude();

                try {
                    Geocoder geocoder = new Geocoder(RegistrationActivity.this, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(),
                            mLastLocation.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

                    currentCountry = "" + addresses.get(0).getCountryName();

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

                getCountryList();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode != MY_PERMISSIONS_REQUEST_READ) {
            return;
        }

        try {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (mLastLocation != null) {
                LOCATION_LATITUDE = "" + mLastLocation.getLatitude();
                LOCATION_LONGITUDE = "" + mLastLocation.getLongitude();

                try {
                    Geocoder geocoder = new Geocoder(RegistrationActivity.this, Locale.getDefault());
                    List<Address> addresses = geocoder.getFromLocation(mLastLocation.getLatitude(),
                            mLastLocation.getLongitude(), 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5

                    currentCountry = "" + addresses.get(0).getCountryName();

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

                getCountryList();
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(RegistrationActivity.this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        enableMyLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        if (mPermissionDenied) {
            showMissingPermissionError();
            mPermissionDenied = false;
        }
    }

    private void showMissingPermissionError() {
        PermissionUtils.PermissionDeniedDialog.newInstance(false).show(getSupportFragmentManager(), "dialog");
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (pDialogOut != null) {
            pDialogOut.dismiss();
        }
    }

    private boolean isValidPassword(final String password) {
        String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!?*/_@#$%^&+=])(?=\\S+$).{6,20}$";
        Pattern pattern = Pattern.compile(PASSWORD_PATTERN);
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    public String trimMessage(String json, String key) {
        String trimmedString = null;
        try {
            JSONObject obj = new JSONObject(json);
            trimmedString = obj.getString(key);
        } catch (JSONException e) {
            e.printStackTrace();
            trimmedString = json;
        }
        return trimmedString;
    }

    public void displayMessage(String toastString) {
        android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
                RegistrationActivity.this);
        alertDialogBuilder.setTitle("Error");
        alertDialogBuilder.setMessage(Html.fromHtml(toastString)).setCancelable(false)
                .setPositiveButton("Retry", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                }).setNegativeButton("Discard", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        onBackPressed();
                    }
                });
        android.app.AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
}