Subversion Repositories SmartDukaan

Rev

Blame | Last modification | View Log | RSS feed

package com.saholic.profittill.main;

import android.Manifest;
import android.app.AlertDialog;
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.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.internal.http.multipart.MultipartEntity;
import com.facebook.Session;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.saholic.profittill.Constants.ProfitTillConstants;
import com.saholic.profittill.R;
import com.saholic.profittill.Utils.AnalyticsUtility;
import com.saholic.profittill.Utils.Utility;
import com.saholic.profittill.Utils.UtilityFunctions;
import com.saholic.profittill.Volley.Analytics;
import com.saholic.profittill.Volley.AnalyticsErrorResponse;
import com.saholic.profittill.Volley.AnalyticsJsonResponse;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ReferrerActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,View.OnClickListener {
    EditText referalCode;
    MixpanelAPI mixpanel;
    Button referrerSend;
    ImageButton remove, remove2;
    String type1;
    TextView supportList;
    ImageView  ivImage, ivImage2;
    GalleryPhoto galleryPhoto;
    CameraPhoto cameraPhoto;
    private int REQUEST_CAMERA_ONE = 2, SELECT_FILE_ONE = 3;
    private String userChoosenTask;
    SharedPreferences userData;
    SharedPreferences apiData;
    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    SharedPreferences.Editor userDataEditor;
    SharedPreferences.Editor apiSettingsEditor;
    SharedPreferences inviteD;
    SharedPreferences.Editor inviteDEditor;
    ArrayList<NameValuePair> nameValuePairsGcm;
    public GoogleApiClient mGoogleApiClient;
    boolean glogout;
    RelativeLayout storeDocument,supportDocument;
    String selectedPath1="";
    String selectedPath2= "";
    HttpEntity resEntity;
    private final String TAG = this.getClass().getName();
    final ArrayList<String> invitationCodeList = new ArrayList<String>();

    ArrayList<NameValuePair> nameValuePairs;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_referrer);
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.White)));
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setCustomView(R.layout.profitmandiicon);
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
        userDataEditor = userData.edit();
        apiSettingsEditor = apiData.edit();
        inviteD = getApplicationContext().getSharedPreferences("Invite", MODE_PRIVATE);
        inviteDEditor = inviteD.edit();
        remove = (ImageButton) findViewById(R.id.remove);
        remove2 = (ImageButton) findViewById(R.id.remove2);
        supportList=(TextView)findViewById(R.id.supportList);
        ivImage = (ImageView) findViewById(R.id.ivImage);
        ivImage2 = (ImageView) findViewById(R.id.ivImage2);
        referalCode = (EditText) findViewById(R.id.referalCode);
        storeDocument=(RelativeLayout)findViewById(R.id.storeDocument);
        storeDocument.setOnClickListener(this);
        supportDocument=(RelativeLayout)findViewById(R.id.supportDocument);
        supportDocument.setOnClickListener(this);
        referrerSend = (Button) findViewById(R.id.referrerSend);
        galleryPhoto = new GalleryPhoto(getApplicationContext());
        cameraPhoto = new CameraPhoto(getApplicationContext());
        mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);

        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
        t.setScreenName("Referrer Screen");
        t.send(new HitBuilders.ScreenViewBuilder().build());
        new Analytics(ProfitTillConstants.ANALYTICS_URL,
                AnalyticsUtility.getAnalyticsRequest(ReferrerActivity.this, userData.getString("id", ""), "Screen", "Referrer", "Referrer Screen"),
                AnalyticsJsonResponse.getAnalyticsRequestInstance(),
                AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(ReferrerActivity.this);

        if (getIntent().getAction() == "Login") {
            new Analytics(ProfitTillConstants.ANALYTICS_URL,
                    AnalyticsUtility.getAnalyticsRequest(ReferrerActivity.this, userData.getString("id", ""), "Notification", "Notification Opened Referrer", getIntent().getExtras().getString("cid")),
                    AnalyticsJsonResponse.getAnalyticsRequestInstance(),
                    AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(ReferrerActivity.this);

            nameValuePairsGcm = new ArrayList<>();
            nameValuePairsGcm.add(new BasicNameValuePair("cid", getIntent().getExtras().getString("cid")));
            nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id", "")));
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
            nameValuePairsGcm.add(new BasicNameValuePair("result", "referrer"));
            getIntent().getExtras().remove("cid");
            new NotificationOpenedData().execute(nameValuePairsGcm);
        } else if (getIntent().getAction() == "31") {
            String emailURL = String.valueOf(getIntent().getData());
            Uri url = Uri.parse(emailURL);
            String campaignId = url.getQueryParameter("campaign");
            if (url.getQueryParameter("intent_type").equalsIgnoreCase("url")) {
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Message/Email")
                        .setAction("Message/Email Opened For User Id " + UtilityFunctions.campaignUserId(url))
                        .setLabel("Campaign Id " + campaignId)
                        .build());
                new Analytics(ProfitTillConstants.ANALYTICS_URL,
                        AnalyticsUtility.getAnalyticsRequest(ReferrerActivity.this, UtilityFunctions.campaignUserId(url), "Message", "Message Opened Referrer", campaignId),
                        AnalyticsJsonResponse.getAnalyticsRequestInstance(),
                        AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(ReferrerActivity.this);

                nameValuePairsGcm = new ArrayList<>();
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", UtilityFunctions.campaignUserId(url)));
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_referrer"));
                new NotificationOpenedData().execute(nameValuePairsGcm);
            } else {
                nameValuePairsGcm = new ArrayList<>();
                nameValuePairsGcm.add(new BasicNameValuePair("user_id", userData.getString("id", "")));
                nameValuePairsGcm.add(new BasicNameValuePair("cid", campaignId));
                nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
                nameValuePairsGcm.add(new BasicNameValuePair("result", "message_opened_referrer"));
                new NotificationOpenedData().execute(nameValuePairsGcm);
            }
        }

        remove.setOnClickListener(this);
        remove2.setOnClickListener(this);

        supportList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                final CharSequence[] items = {"Sales tax/ VAT registration","Service tax registration","Excise registration","Trade licenses ","Certificate/registration under Shops and Establishment Act","License for undertaking retail trade (like tehbazari and similar license for hawkers) from Government Authorities/Local Self Government Bodies or","Certificate of incorporation or registration as a society or registration as public trust for their self consumption, if purchase is made for self consumption."};
                
                AlertDialog.Builder builder = new AlertDialog.Builder(ReferrerActivity.this);
                builder.setTitle("Document List");
                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {

                    }
                });
                AlertDialog alert = builder.create();
                ListView listView=alert.getListView();
                listView.setDivider(new ColorDrawable((getResources().getColor(R.color.Silver)))); // set color
                listView.setDividerHeight(2);
                listView.setOverscrollFooter(new ColorDrawable(Color.TRANSPARENT));
                listView.setFooterDividersEnabled(false);
                alert.show();
            }});
                referalCode.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        inputMethodManager.showSoftInput(referalCode, InputMethodManager.SHOW_IMPLICIT);
                        referalCode.requestFocus();
                    }
                });


                JSONObject props = new JSONObject();
                try {
                    props.put("Referrer", "Referrer Screen");
                    mixpanel.track("Referrer Screen", props);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
                type1 = userData.getString("type", null);

                if (type1 != null && type1.equalsIgnoreCase("google")) {
                    mGoogleApiClient = new GoogleApiClient.Builder(this)
                            .addConnectionCallbacks(this)
                            .addOnConnectionFailedListener(this).addApi(Plus.API)
                            .addScope(Plus.SCOPE_PLUS_LOGIN).build();
                    mGoogleApiClient.connect();
                }


                referrerSend.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (!referalCode.getText().toString().equals("")) {
                                new PushReferrerData().execute(referalCode.getText().toString());
                            } else if (!selectedPath1.equals("")&& !selectedPath2.equals("")) {
                                new UploadImage().execute();
                            } else {
                                Toast.makeText(getApplicationContext(), "One field is required", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }});
            }

            public void requestCamera() {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.CAMERA)
                            != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA},
                                101);
                    }
                }
            }


            @Override
            protected void onActivityResult(int requestCode, int resultCode, Intent data) {

                if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
                    String Photopath = cameraPhoto.getPhotoPath();
                    selectedPath1 = Photopath;
                    try {
                        Bitmap bitmap = ImageLoader.init().from(Photopath).requestSize(512, 512).getBitmap();
                        final int sizeInBytes = bitmap.getByteCount();
                        Log.d("Tag", String.valueOf(sizeInBytes));
                        ivImage.setImageBitmap(bitmap);
                        remove.setVisibility(View.VISIBLE);
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "Error while loading Photo", Toast.LENGTH_LONG).show();
                    }
                } else if (requestCode == SELECT_FILE && resultCode == RESULT_OK) {
                    Uri selectedImageUri = data.getData();
                    galleryPhoto.setPhotoUri(selectedImageUri);
                    String Photopath = galleryPhoto.getPath();
                    selectedPath1 = Photopath;
                    try {
                        Bitmap bitmap = ImageLoader.init().from(Photopath).requestSize(512, 512).getBitmap();
                        ivImage.setImageBitmap(bitmap);
                        remove.setVisibility(View.VISIBLE);
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "Error while loading Photo", Toast.LENGTH_LONG).show();
                    }

                } else if (requestCode == REQUEST_CAMERA_ONE && resultCode == RESULT_OK) {
                    String Photopath = cameraPhoto.getPhotoPath();
                    selectedPath2 = Photopath;
                    try {
                        Bitmap bitmap = ImageLoader.init().from(Photopath).requestSize(512, 512).getBitmap();
                        ivImage2.setImageBitmap(bitmap);
                        remove2.setVisibility(View.VISIBLE);
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "Error while loading Photo", Toast.LENGTH_LONG).show();
                    }

                } else if (requestCode == SELECT_FILE_ONE && resultCode == RESULT_OK) {
                    Uri selectedImageUri = data.getData();
                    galleryPhoto.setPhotoUri(selectedImageUri);
                    String Photopath = galleryPhoto.getPath();
                    selectedPath2 = Photopath;
                    try {
                        Bitmap bitmap = ImageLoader.init().from(Photopath).requestSize(512, 512).getBitmap();
                        ivImage2.setImageBitmap(bitmap);
                        remove2.setVisibility(View.VISIBLE);
                    } catch (FileNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "Error while loading Photo", Toast.LENGTH_LONG).show();
                    }
                }

            }

            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                getMenuInflater().inflate(R.menu.menu_referrer, menu);
                return true;
            }

            @Override
            public boolean onOptionsItemSelected(MenuItem item) {

                int id = item.getItemId();
                if (id == R.id.action_settings) {
                    return true;
                }
                return super.onOptionsItemSelected(item);
            }

            @Override
            public void onConnected(Bundle bundle) {

            }

            @Override
            public void onConnectionSuspended(int i) {

            }


            @Override
            public void onClick(View v) {
                if (v == storeDocument) {
                    requestCamera();
                    Utility.checkPermission(ReferrerActivity.this);
                    final CharSequence[] items = {"Take Photo", "Choose from Library",
                            "Cancel"};

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Add Photo!");
                    builder.setItems(items, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            boolean result = Utility.checkPermission(ReferrerActivity.this);
                            if (items[item].equals("Take Photo")) {
                                userChoosenTask = "Take Photo";
                                if (result) {

                                    try {
                                        startActivityForResult(cameraPhoto.takePhotoIntent(), REQUEST_CAMERA);
                                        cameraPhoto.addToGallery();
                                    } catch (IOException e) {
                                        Toast.makeText(getApplicationContext(), "Something Wrong while taking photo", Toast.LENGTH_LONG).show();
                                    }
                                }
                            } else if (items[item].equals("Choose from Library")) {
                                userChoosenTask = "Choose from Library";
                                if (result) {
                                    startActivityForResult(galleryPhoto.openGalleryIntent(), SELECT_FILE);
                                }
                            } else if (items[item].equals("Cancel")) {
                                dialog.dismiss();
                            }
                        }
                    });
                    builder.show();
                } else if (v == supportDocument) {
                    requestCamera();
                    Utility.checkPermission(ReferrerActivity.this);

                    final CharSequence[] items = {"Take Photo", "Choose from Library",
                            "Cancel"};

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Add Photo!");
                    builder.setItems(items, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            boolean result = Utility.checkPermission(ReferrerActivity.this);

                            if (items[item].equals("Take Photo")) {
                                userChoosenTask = "Take Photo";
                                if (result) {
                                    try {
                                        startActivityForResult(cameraPhoto.takePhotoIntent(), REQUEST_CAMERA_ONE);
                                        cameraPhoto.addToGallery();
                                    } catch (IOException e) {
                                        Toast.makeText(getApplicationContext(), "Something Wrong while taking photo", Toast.LENGTH_LONG).show();
                                    }

                                }
                            } else if (items[item].equals("Choose from Library")) {
                                userChoosenTask = "Choose from Library";
                                if (result) {
                                    startActivityForResult(galleryPhoto.openGalleryIntent(), SELECT_FILE_ONE);
                                }
                            } else if (items[item].equals("Cancel")) {
                                dialog.dismiss();
                            }
                        }
                    });
                    builder.show();
                } else if (v == remove) {
                    selectedPath1="";
                    ivImage.setImageBitmap(null);
                    remove.setVisibility(View.INVISIBLE);
                } else if (v == remove2) {
                    ivImage2.setImageBitmap(null);
                    selectedPath2="";
                    remove2.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {

            }


    class UploadImage extends AsyncTask<String, Integer, JSONObject> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd2 = new ProgressDialog(ReferrerActivity.this);
            pd2.setMessage("Please wait...");
            pd2.setCancelable(false);
            pd2.show();

        }

        @Override
        protected JSONObject doInBackground(String... arg0) {
            String id = null;
            if (isInternetOn()) {
                byte[] BYTE;
                Bitmap bitmap = null;
                try {
                    bitmap = ImageLoader.init().from(selectedPath1).requestSize(512, 512).getBitmap();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                final int sizeInBytes = bitmap.getByteCount();
                double qualityFactor = 1;
                if (sizeInBytes > 200 * 1024) {
                    qualityFactor = Math.cbrt(Math.cbrt((double) sizeInBytes / (double) (200 * 1024)));
                }
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, (int) (100.0 / qualityFactor), bos);
                BYTE = bos.toByteArray();
                String encodedImage = Base64.encodeToString(BYTE, Base64.DEFAULT);
                Log.d("Tag", encodedImage);

                Bitmap bitmap2 = null;
                try {
                    bitmap2 = ImageLoader.init().from(selectedPath2).requestSize(512, 512).getBitmap();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                final int sizeInBytes2 = bitmap2.getByteCount();
                double qualityFactors = 1;
                if (sizeInBytes2 > 200 * 1024) {
                    qualityFactors = Math.cbrt(Math.cbrt((double) sizeInBytes2 / (double) (200 * 1024)));
                }
                ByteArrayOutputStream boss = new ByteArrayOutputStream();
                bitmap2.compress(Bitmap.CompressFormat.JPEG, (int) (100.0 / qualityFactors), boss);
                BYTE = boss.toByteArray();
                String encodedImage2 = Base64.encodeToString(BYTE, Base64.DEFAULT);
                Log.d("Tag", encodedImage2);
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                    String updateURL = apiData.getString("useredit.url", "");
                    String url = updateURL + userData.getString("id", "");
                    nameValuePairs.add(new BasicNameValuePair("id", userData.getString("id", null)));
                    nameValuePairs.add(new BasicNameValuePair("storeImage", encodedImage));
                    nameValuePairs.add(new BasicNameValuePair("supportDocument", encodedImage2));
                    HttpPost httppost = new HttpPost(url);
                    httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    int status = response.getStatusLine().getStatusCode();
                    JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
                    return jObjGmail;

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

                }
            }
            Toast.makeText(getApplicationContext(),"Internet problem",Toast.LENGTH_LONG).show();
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            pd2.dismiss();
            if(result==null){
                finish();
            }
            try {
                if (result.getBoolean("success")){
                    Toast.makeText(getApplicationContext(), "Image Upload Sucessfully", Toast.LENGTH_LONG).show();
                    Intent i = new Intent(ReferrerActivity.this, PendingActivity.class);
                    startActivity(i);
                } else {
                    Toast.makeText(getApplicationContext(), "Error While Uploading", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    class PushReferrerData extends AsyncTask<String, Integer, String> {

                @Override
                protected void onPreExecute() {
                    super.onPreExecute();
                    referrerSend.setEnabled(false);
                    pd2 = new ProgressDialog(ReferrerActivity.this);
                    pd2.setMessage("Please wait...");
                    pd2.setCancelable(false);
                    pd2.show();

                }

                @Override
                protected String doInBackground(String... arg0) {
                    String id = null;
                    if (isInternetOn()) {

                        try {
                            HttpClient httpclient = new DefaultHttpClient();
                            nameValuePairs = new ArrayList<>();
                            String updateURL = apiData.getString("useredit.url", "");
                            String url = updateURL + userData.getString("id", "");
                            nameValuePairs.add(new BasicNameValuePair("id", userData.getString("id", null)));
                            nameValuePairs.add(new BasicNameValuePair("referrer", arg0[0]));
                            HttpPost httppost = new HttpPost(url);
                            httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            int status = response.getStatusLine().getStatusCode();
                            JSONObject jObjGmail = new JSONObject(EntityUtils.toString(entity));
                            System.out.println("JSON Object in referrer " + jObjGmail.toString());
                            String success = jObjGmail.getString("success");
                            if (status == 200) {
                                inviteDEditor.putString("referrerCode", arg0[0]);
                                inviteDEditor.commit();
                                Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                                        GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
                                t.send(new HitBuilders.EventBuilder()
                                        .setCategory("Referrer ")
                                        .setAction("Referrer Saved Successfully")
                                        .setLabel("Referrer for User" + userData.getString("id", null) + " is " + arg0[0])
                                        .build());
                            }
                            if (success.equalsIgnoreCase("true")) {
                                MixpanelAPI mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
                                JSONObject props = new JSONObject();
                                try {
                                    props.put("Referrer", "Referrer Saved Successfully");
                                    mixpanel.track("Referrer Saved", props);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                userDataEditor.putString("referralCodeRequired", "false");
                                userDataEditor.commit();
                                return "true";
                            } else {
                                userDataEditor.putString("referralCodeRequired", "true");
                                userDataEditor.commit();
                                return "false";
                            }

                        } catch (Exception e) {
                            Log.e("Fail 1", e.toString());
                            return "false";
                        }

                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    pd2.dismiss();
                    if (result.equalsIgnoreCase("true")) {

                        new Analytics(ProfitTillConstants.ANALYTICS_URL,
                                AnalyticsUtility.getAnalyticsRequest(ReferrerActivity.this, userData.getString("id", ""), "Clicks", "Referrer", "Invite Code Entered"),
                                AnalyticsJsonResponse.getAnalyticsRequestInstance(),
                                AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(ReferrerActivity.this);

                        if (userData.getString("message", "false").equalsIgnoreCase("true")) {
                            nameValuePairs = new ArrayList<NameValuePair>();
                            Intent i = new Intent(ReferrerActivity.this, MobileNumber.class);
                            i.putExtra("displayView", "7");
                            startActivity(i);
                        } else {
                            if (!(userData.getString("mobileNumber", "").isEmpty())) {
                                Intent i = new Intent(ReferrerActivity.this, MobileVerificationFirstTime.class);
                                i.putExtra("numberVerification", userData.getString("mobileNumber", ""));
                                startActivity(i);
                            } else {
                                Intent i = new Intent(ReferrerActivity.this, MainActivity.class);
                                i.putExtra("displayView", "7");
                                startActivity(i);

                            }
                        }
                    } else {
                        referrerSend.setEnabled(true);
                        referalCode.setError("Incorrect Code");
                    }
                }
            }




            ProgressDialog pd2;

            @Override
            public void onBackPressed() {
                new AlertDialog.Builder(this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Exit!")
                        .setMessage("Are you sure you want to sign out?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                JSONObject props = new JSONObject();
                                try {
                                    mixpanel.identify(userData.getString("id", null));
                                    props.put("Screen", "Signing Out");
                                    mixpanel.track("Signing Out Referrer", props);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                                if (type1.equalsIgnoreCase("facebook")) {
                                    Log.d("fblogout", "logout");
                                    if (Session.getActiveSession() != null) {
                                        Session.getActiveSession().closeAndClearTokenInformation();
                                    }
                                    Session.setActiveSession(null);
                                    userDataEditor.clear().commit();
                                    startActivity(new Intent(ReferrerActivity.this, LoginActivity.class));
                                } else {
                                    Log.d("gmailLogout", "logout");
                                    signOutFromGplus();
                                    if (glogout == true) {
                                        startActivity(new Intent(ReferrerActivity.this, LoginActivity.class));
                                    }
                                }

                            }

                        })
                        .setNegativeButton("No", null)
                        .show();
            }

            public void signOutFromGplus() {
                if (mGoogleApiClient.isConnected()) {
                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                    mGoogleApiClient.disconnect();
                    mGoogleApiClient.connect();
                    glogout = true;
                    userDataEditor.clear().commit();
                } else {
                    glogout = false;
                }
            }

            public final boolean isInternetOn() {

                ConnectivityManager connection =
                        (ConnectivityManager) getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);

                if (connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                        connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                        connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
                    return true;

                } else if (
                        connection.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                                connection.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
                    return false;
                }
                return false;
            }


            class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {

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

                }

                @Override
                protected String doInBackground(ArrayList<NameValuePair>... arg0) {

                    try {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost(apiData.getString("notication.data.url", "http://api.profittill.com/pushnotifications/add"));
                        httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                        httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        int status = response.getStatusLine().getStatusCode();

                        if (status == 200) {
                            Log.d("Notification Opened", "Notication opened and sent to server");
                            Log.d("ResponseCode GCM ", status + "");
                        } else {
                            Log.d("ResponseCode GCM ", status + "");
                        }

                        nameValuePairsGcm.clear();
                        Log.e("pass 1", "connection success ");
                    } catch (Exception e) {
                        Log.e("Fail 1", e.toString());

                    }
                    return "success";
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    Log.d("Notification Opened", "Notication opened and login page");
                }
            }

        }