com.instiwork.RegistrationFacebookActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.instiwork.RegistrationFacebookActivity.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.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.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.RadioButton;
import android.widget.RadioGroup;
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.google.ads.conversiontracking.AdWordsRemarketingReporter;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
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.CornerMoldTransformation;
import com.instiwork.helper.PermissionUtils;
import com.squareup.picasso.Picasso;

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

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
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;

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

    RobotoLight license;
    LinearLayout ll_license, ll_image_selection;
    RecyclerView selecteddata;
    TextView dateOfBirth;
    EditText fstName, companyName, email, mobile;
    ImageView pro_img;
    RadioGroup gender;
    RadioButton maleRadio, femaleRadio;
    String genderData = "";
    String gcmToken = "";
    SharedPreferences appSharedPref = null;
    public final String TAG = "RegistrationFacebookActivity";
    ProgressDialog pDialogOut;
    LicenseHorizontalAdapter licenseHorizontalAdapter;
    String imgPath = "", license_ = "", result = "", status = "", message = "", dob = "Birth date";
    LinkedList<JSONObject> licenseLinkedList;

    // 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;
    RobotoBold txt_terms_conditions;
    WebView webViewTermsUse;

    ProgressBar pBarPrivacyPolicy, pBarTermsUse;
    RobotoLight txtPrivacyPolicy, txtTermsUse, txt_fees;
    Dialog mBottomSheetDialogTermsUse = null;

    String currentCountry = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_facebook);

        pDialogOut = new ProgressDialog(RegistrationFacebookActivity.this);
        pDialogOut.setMessage("Signing up...");

        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);
        maleRadio = (RadioButton) findViewById(R.id.malehit);
        femaleRadio = (RadioButton) findViewById(R.id.frmalrhit);
        fstName = (EditText) findViewById(R.id.first_name);
        companyName = (EditText) findViewById(R.id.company_name);
        email = (EditText) findViewById(R.id.email);
        mobile = (EditText) findViewById(R.id.mobile);

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

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

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

        try {

            if (getIntent().getStringExtra("FB_NAME").equalsIgnoreCase("")) {
                fstName.setText("");
                fstName.setClickable(true);
                fstName.setEnabled(true);
            } else {
                fstName.setText(getIntent().getStringExtra("FB_NAME"));
                fstName.setClickable(false);
                fstName.setEnabled(false);
            }
            if (getIntent().getStringExtra("FB_EMAIL").equalsIgnoreCase("")) {
                email.setText("");
                email.setClickable(true);
                email.setEnabled(true);
            } else {
                email.setText(getIntent().getStringExtra("FB_EMAIL"));
                email.setClickable(false);
                email.setEnabled(false);
            }
            //            if (getIntent().getStringExtra("FB_BIRTHDAY").equalsIgnoreCase("")) {
            //                dateOfBirth.setText(dob);
            //                dateOfBirth.setClickable(true);
            //            } else {
            //                dateOfBirth.setText(getIntent().getStringExtra("FB_BIRTHDAY"));
            //                dateOfBirth.setClickable(false);
            //            }
            if (getIntent().getStringExtra("FB_GENDER").equalsIgnoreCase("")) {
                gender.setClickable(true);
                maleRadio.setClickable(true);
                femaleRadio.setClickable(true);
            } else {
                gender.setClickable(false);
                maleRadio.setClickable(false);
                femaleRadio.setClickable(false);
                if (getIntent().getStringExtra("FB_GENDER").equalsIgnoreCase("male")) {
                    genderData = "" + 1;
                    maleRadio.setChecked(true);
                    femaleRadio.setChecked(false);
                } else if (getIntent().getStringExtra("FB_GENDER").equalsIgnoreCase("female")) {
                    genderData = "" + 2;
                    maleRadio.setChecked(false);
                    femaleRadio.setChecked(true);
                }
            }
            if (getIntent().getStringExtra("FB_IMG").equalsIgnoreCase("")) {
                ll_image_selection.setClickable(true);
            } else {
                ll_image_selection.setClickable(false);
                imgPath = getIntent().getStringExtra("FB_IMG");
                Picasso.with(RegistrationFacebookActivity.this).load(getIntent().getStringExtra("FB_IMG"))
                        .transform(new CornerMoldTransformation(24, 0, CornerMoldTransformation.CornerType.ALL))
                        .fit().centerCrop().placeholder(R.mipmap.ic_launcher).fit().centerCrop().into(pro_img);
            }

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

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

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

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

            @Override
            public void onClick(View v) {
                android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
                        RegistrationFacebookActivity.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 View.OnClickListener() {

            @Override
            public void onClick(View v) {
                android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
                        RegistrationFacebookActivity.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();
            }
        });

        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_license.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RegistrationFacebookActivity.this, LicenseActivity.class);
                startActivityForResult(i, 420);
            }
        });

        dateOfBirth.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Calendar today = Calendar.getInstance();
                //                today.add(Calendar.YEAR, -14);

                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(RegistrationFacebookActivity.this);
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        //                        dateOfBirth.setText("" + dPicker.getDayOfMonth() + "/" + (dPicker.getMonth() + 1) + "/" + dPicker.getYear());
                        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(dob);
                    }
                });
                builder.setView(dialoglayout);
                builder.show();
            }
        });

        gender.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                int selectedId = gender.getCheckedRadioButtonId();
                if (selectedId == maleRadio.getId()) {
                    genderData = "" + 1;
                } else if (selectedId == femaleRadio.getId()) {
                    genderData = "" + 2;
                } else {
                    genderData = "";
                }

            }
        });

        findViewById(R.id.loginBttn).setOnClickListener(new View.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 (!android.util.Patterns.PHONE.matcher(mobile.getText().toString().trim())
                                    .matches()) {
                                mobile.setError("Please enter valid mobile number.");
                                mobile.requestFocus();
                            } else {
                                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()) {
                                                try {
                                                    gcmToken = appSharedPref.getString("GCM_TOKEN", "");
                                                    String date[] = dateOfBirth.getText().toString().trim()
                                                            .split("/");

                                                    final String URL = InstiworkConstants.URL_DOMAIN
                                                            + "Login_ios/facebooksignup?name="
                                                            + URLEncoder.encode(
                                                                    fstName.getText().toString().trim(), "UTF-8")
                                                            + "&companyname="
                                                            + URLEncoder.encode(
                                                                    companyName.getText().toString().trim(),
                                                                    "UTF-8")
                                                            + "&email="
                                                            + URLEncoder.encode(email.getText().toString().trim(),
                                                                    "UTF-8")
                                                            + "&gender=" + genderData + "&year=" + date[2]
                                                            + "&month=" + date[0] + "&date=" + date[1] + "&license="
                                                            + license_ + "&facebook_id="
                                                            + getIntent().getStringExtra("FB_ID")
                                                            + "&facebook_token="
                                                            + getIntent().getStringExtra("FB_ACCESS_TOKEN")
                                                            + "&devicetoken="
                                                            + getIntent().getStringExtra("FB_DEVICE_TOKEN")
                                                            + "&devicetype=2" + "&contact="
                                                            + URLEncoder.encode(mobile.getText().toString().trim(),
                                                                    "UTF-8")
                                                            + "&image=" + getIntent().getStringExtra("FB_IMG")
                                                            + "&lat=" + LOCATION_LATITUDE + "&lng="
                                                            + LOCATION_LONGITUDE + "&country2_code="
                                                            + country_2_code + "&country_id=" + country_id;
                                                    Logger.showMessage(TAG, "FBREG  " + URL);

                                                    pDialogOut.show();

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

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

                                                    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();
                                    }
                                }
                            }
                        } else {
                            email.setError("Please enter valid email.");
                            email.requestFocus();
                        }
                    }
                }
            }
        });

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

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

        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(RegistrationFacebookActivity.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(
                                    RegistrationFacebookActivity.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);
    }

    @Override
    public void onBackPressed() {
        if (getIntent().getStringExtra("FromIntent").equalsIgnoreCase("LoginActivity")) {
            Intent backIntent = new Intent(RegistrationFacebookActivity.this, LoginActivity.class);
            startActivity(backIntent);
            finish();
        } else if (getIntent().getStringExtra("FromIntent").equalsIgnoreCase("RegistrationActivity")) {
            Intent backIntent = new Intent(RegistrationFacebookActivity.this, RegistrationActivity.class);
            startActivity(backIntent);
            finish();
        } else {
            super.onBackPressed();
        }
    }

    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) {
        }

    }

    public void login_User(final String URL) {
        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);
                        pDialogOut.hide();

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

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

                        try {
                            InstiworkApplication.getInstance().setSelectedLicenseArray(null);
                            if (response.getJSONObject("response").getString("status")
                                    .equalsIgnoreCase("Success")) {
                                InstiworkApplication.getInstance()
                                        .setUSER_ID(response.getJSONObject("response").getString("id"));
                                InstiworkApplication.getInstance()
                                        .setUSER_NAME(response.getJSONObject("response").getString("name"));
                                InstiworkApplication.getInstance().setCOMPANY_NAME(
                                        response.getJSONObject("response").getString("companyname"));
                                InstiworkApplication.getInstance()
                                        .setUSER_EMAIL(response.getJSONObject("response").getString("email"));
                                InstiworkApplication.getInstance()
                                        .setMOBILE_NO(response.getJSONObject("response").getString("contact"));
                                try {
                                    InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                            response.getJSONObject("response").getString("distance"));
                                    InstiworkApplication.getInstance()
                                            .setUnit_user(response.getJSONObject("response").getString("unit"));
                                } catch (Exception e) {
                                    try {
                                        InstiworkApplication.getInstance().setJOB_SEARCH_RADIUS(
                                                response.getJSONObject("response").getString("distance_user"));
                                        InstiworkApplication.getInstance().setUnit_user(
                                                response.getJSONObject("response").getString("unit_user"));
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                    }
                                }

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

                                InstiworkApplication.getInstance()
                                        .setUSER_IMG(response.getJSONObject("response").getString("profileimage"));
                                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("id"));
                                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_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());
                                }

                                Toast.makeText(RegistrationFacebookActivity.this, "Registered successfully",
                                        Toast.LENGTH_SHORT).show();
                                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 {
                                pDialogOut.hide();
                                //                                Toast.makeText(RegistrationFacebookActivity.this, response.getJSONObject("response").getString("message"), Toast.LENGTH_SHORT).show();
                                //                                Snackbar.make(findViewById(android.R.id.content), response.getString("details"), Snackbar.LENGTH_LONG)
                                //                                        .setActionTextColor(Color.RED)
                                //                                        .show();
                                try {
                                    displayMessage(response.getString("details"));
                                    //                                Snackbar.make(findViewById(android.R.id.content), response.getString("details"), Snackbar.LENGTH_LONG)
                                    //                                        .setActionTextColor(Color.RED)
                                    //                                        .show();
                                } catch (Exception ee) {
                                    ee.printStackTrace();
                                    try {
                                        displayMessage(response.getString("message"));
                                    } catch (Exception eee) {
                                        eee.printStackTrace();
                                    }
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            try {
                                displayMessage(response.getString("details"));
                                //                                Snackbar.make(findViewById(android.R.id.content), response.getString("details"), Snackbar.LENGTH_LONG)
                                //                                        .setActionTextColor(Color.RED)
                                //                                        .show();
                            } catch (Exception ee) {
                                ee.printStackTrace();
                                try {
                                    displayMessage(response.getString("message"));
                                } catch (Exception eee) {
                                    eee.printStackTrace();
                                }
                            }
                            pDialogOut.hide();
                        }
                    }
                }, new Response.ErrorListener() {

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

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

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

                        if (error instanceof NoConnectionError) {
                            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                                    RegistrationFacebookActivity.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();

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

                                    txt_terms_conditions.setEnabled(false);
                                    findViewById(R.id.help_dob).setEnabled(false);
                                    findViewById(R.id.help_license).setEnabled(false);
                                    ll_license.setEnabled(false);
                                    dateOfBirth.setEnabled(false);
                                    findViewById(R.id.footer).setEnabled(false);
                                    findViewById(R.id.loginBttn).setEnabled(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 {
                            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 String trimMessage(String json, String key) {
        String trimmedString = "";
        try {
            JSONObject obj = new JSONObject(json);
            trimmedString = obj.getJSONObject("error").getString(key);
        } catch (JSONException e) {
            e.printStackTrace();
            return json;
        }
        return trimmedString;
    }

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

    public void dialogTermsUse() {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.dialog_terms_use, null);
        mBottomSheetDialogTermsUse = new Dialog(RegistrationFacebookActivity.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 View.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(
                                    RegistrationFacebookActivity.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);
    }

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

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.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(RegistrationFacebookActivity.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");
                Picasso.with(RegistrationFacebookActivity.this).load("file://" + data.getStringExtra("data"))
                        .transform(new CornerMoldTransformation(24, 0, CornerMoldTransformation.CornerType.ALL))
                        .fit().centerCrop().placeholder(R.mipmap.ic_launcher).fit().centerCrop().into(pro_img);
                Logger.showMessage(TAG, "Image Taker" + imgPath);
            } catch (Exception e) {
                Logger.showMessage(TAG, "Image Taker Exception " + imgPath + "  \n" + e.toString());
            }
        } else {
        }
    }

    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(RegistrationFacebookActivity.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(RegistrationFacebookActivity.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(RegistrationFacebookActivity.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();
    }
}