Rev 16278 | Blame | Last modification | View Log | RSS feed
package com.saholic.profittill.main;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.graphics.Color;import android.net.ConnectivityManager;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.text.InputType;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.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;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.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.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.JSONException;import org.json.JSONObject;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;public class ReferrerActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {EditText referalCode;EditText mobileNumber;MixpanelAPI mixpanel;TextView inviteMessage,inviteMessage1,inviteNumber,giveus,thanks,incorrect;Button referrerSend,mobileNumberSend;String type1;String invitationCode;SharedPreferences userData;SharedPreferences apiData;SharedPreferences.Editor userDataEditor;SharedPreferences.Editor apiSettingsEditor;SharedPreferences inviteD;SharedPreferences.Editor inviteDEditor;ArrayList<NameValuePair> nameValuePairsGcm;public GoogleApiClient mGoogleApiClient;boolean glogout;final ArrayList<String> invitationCodeList = new ArrayList<String>();boolean FLAG=false;ArrayList<NameValuePair> nameValuePairs;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_referrer);getSupportActionBar().hide();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();inviteMessage=(TextView)findViewById(R.id.inviteMessage);inviteMessage1=(TextView)findViewById(R.id.inviteMessage1);inviteNumber=(TextView)findViewById(R.id.inviteNumber);giveus=(TextView)findViewById(R.id.giveus);thanks=(TextView)findViewById(R.id.thanks);incorrect=(TextView)findViewById(R.id.incorrect);referalCode=(EditText)findViewById(R.id.referralCode);mobileNumber=(EditText)findViewById(R.id.mobileNumberReferrer);referrerSend =(Button)findViewById(R.id.referrerSend);mobileNumberSend =(Button)findViewById(R.id.mobileNumberReferrerSend);mixpanel= MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);inviteMessage.setText(apiData.getString("referralinvite.text", "Got your Invite Code?"));inviteMessage1.setText(apiData.getString("no.referralinvite", "Haven't got the code..."));giveus.setText(apiData.getString("referralMobileNumber.text","Leave ur no & we'll get back to you"));inviteNumber.setVisibility(View.VISIBLE);inviteNumber.setText("Call " + apiData.getString("contactus.number", "") + " now");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);referalCode.setInputType(0);mobileNumber.setInputType(0);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);}referalCode.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);inputMethodManager.showSoftInput(referalCode, InputMethodManager.SHOW_IMPLICIT);referalCode.requestFocus();}});mobileNumber.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {mobileNumber.setInputType(InputType.TYPE_CLASS_PHONE);}});inviteNumber.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new Analytics(ProfitTillConstants.ANALYTICS_URL,AnalyticsUtility.getAnalyticsRequest(ReferrerActivity.this, userData.getString("id", ""), "Clicks", "Referrer", "Call to get Invite Code"),AnalyticsJsonResponse.getAnalyticsRequestInstance(),AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(ReferrerActivity.this);Intent callIntent = new Intent(Intent.ACTION_CALL);callIntent.setData(Uri.parse("tel:0" + apiData.getString("contactus.number", "")));startActivity(callIntent);}});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();}referalCode.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (event.getAction() == KeyEvent.ACTION_DOWN){switch (keyCode){case KeyEvent.KEYCODE_DPAD_CENTER:case KeyEvent.KEYCODE_ENTER:if(referalCode.getText().toString().equalsIgnoreCase("")) {incorrect.setVisibility(View.VISIBLE);incorrect.setText(apiData.getString("incorrect.referralinvite","Incorrect Code"));incorrect.setTextColor(Color.RED);referalCode.setHint("Retry");InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(referalCode.getWindowToken(), 0);}else{if(isInternetOn()) {InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(referalCode.getWindowToken(), 0);new PushReferrerData().execute(referalCode.getText().toString());}else{InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(referalCode.getWindowToken(), 0);Toast.makeText(getApplicationContext(), "No internet connection. Please try again.", Toast.LENGTH_SHORT).show();}}return true;default:break;}}return false;}});mobileNumber.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (event.getAction() == KeyEvent.ACTION_DOWN){switch (keyCode){case KeyEvent.KEYCODE_DPAD_CENTER:case KeyEvent.KEYCODE_ENTER:if(mobileNumber.getText().toString().length()==10){if(isInternetOn()) {incorrect.setVisibility(View.GONE);referalCode.setHint("Enter Invite Code");InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mobileNumber.getWindowToken(), 0);new pushVerification().execute();}else{InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mobileNumber.getWindowToken(), 0);Toast.makeText(getApplicationContext(), "No internet connection. Please try again.", Toast.LENGTH_SHORT).show();}}else{InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mobileNumber.getWindowToken(), 0);Toast.makeText(getApplicationContext(), "Mobile Number not valid.", Toast.LENGTH_SHORT).show();}return true;default:break;}}return false;}});referrerSend.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if(referalCode.getText().toString().equalsIgnoreCase("")) {incorrect.setVisibility(View.VISIBLE);incorrect.setText(apiData.getString("incorrect.referralinvite","Incorrect Code"));incorrect.setTextColor(Color.RED);referalCode.setHint("Retry");InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(referalCode.getWindowToken(), 0);}else{if(isInternetOn()) {InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(referalCode.getWindowToken(), 0);new PushReferrerData().execute(referalCode.getText().toString());}else{InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(referalCode.getWindowToken(), 0);Toast.makeText(getApplicationContext(), "No internet connection. Please try again.", Toast.LENGTH_SHORT).show();}}}});mobileNumberSend.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if(mobileNumber.getText().toString().length()==10){if(isInternetOn()) {InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mobileNumber.getWindowToken(), 0);incorrect.setVisibility(View.GONE);referalCode.setHint("Enter Invite Code");new pushVerification().execute();}else{InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mobileNumber.getWindowToken(), 0);Toast.makeText(getApplicationContext(), "No internet connection. Please try again.", Toast.LENGTH_SHORT).show();}}else{InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(mobileNumber.getWindowToken(), 0);Toast.makeText(getApplicationContext(), "Mobile Number not valid.", Toast.LENGTH_SHORT).show();}}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.menu_referrer, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}@Overridepublic void onConnected(Bundle bundle) {}@Overridepublic void onConnectionSuspended(int i) {}@Overridepublic void onConnectionFailed(ConnectionResult connectionResult) {}class PushReferrerData extends AsyncTask<String, Integer, String> {@Overrideprotected void onPreExecute() {super.onPreExecute();referrerSend.setEnabled(false);referalCode.setInputType(0);mobileNumber.setInputType(0);pd2 = new ProgressDialog(ReferrerActivity.this);pd2.setMessage("Please wait...");pd2.setCancelable(false);pd2.show();}@Overrideprotected String doInBackground(String... arg0) {String id=null;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";}}@Overrideprotected 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")) {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);incorrect.setVisibility(View.VISIBLE);incorrect.setText(apiData.getString("incorrect.referralinvite","Incorrect Code"));incorrect.setTextColor(Color.RED);referalCode.setHint("Retry");}}}class pushVerification extends AsyncTask<String, Integer, String> {@Overrideprotected void onPreExecute() {super.onPreExecute();JSONObject props = new JSONObject();try {mixpanel.identify(userData.getString("id",null));props.put("Screen", "Mobile Entered Referrer");mixpanel.track("Mobile Number Entered Referrer",props);} catch (JSONException e) {e.printStackTrace();}referalCode.setInputType(0);mobileNumber.setInputType(0);pd2 = new ProgressDialog(ReferrerActivity.this);pd2.setMessage("Please wait...");pd2.setCancelable(false);pd2.show();}@Overrideprotected String doInBackground(String... arg0) {HttpClient httpclient = new DefaultHttpClient();try {ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();SimpleDateFormat sdf = new SimpleDateFormat(ProfitTillConstants.SQL_DATE_FORMAT);String dateUpdated = sdf.format(new Date());nameValuePairs.add(new BasicNameValuePair("id",userData.getString("id","")));nameValuePairs.add(new BasicNameValuePair("mobile_number",mobileNumber.getText().toString()));nameValuePairs.add(new BasicNameValuePair("mobile_number_last_updated",dateUpdated));String updateURL = apiData.getString("useredit.url","");String url = updateURL+userData.getString("id","");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 mobile " + jObjGmail.toString());String success = jObjGmail.getString("success");if(status == 200){Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(GoogleAnalyticsTracker.TrackerName.APP_TRACKER);t.send(new HitBuilders.EventBuilder().setCategory("First Time Mobile Entered ").setAction("Number entered").setLabel("First Time Mobile entered").build());new Analytics(ProfitTillConstants.ANALYTICS_URL,AnalyticsUtility.getAnalyticsRequest(ReferrerActivity.this, userData.getString("id", ""), "Clicks", "Referrer", "Number Entered"),AnalyticsJsonResponse.getAnalyticsRequestInstance(),AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(ReferrerActivity.this);}if(success.equalsIgnoreCase("true")){userDataEditor.putString("message","false");;userDataEditor.putString("mobileNumber",mobileNumber.getText().toString());userDataEditor.commit();return "true";}else{userDataEditor.putString("message","true");;userDataEditor.commit();return "false";}} catch (ClientProtocolException e) {return "false";} catch (IOException e) {return "false";}catch (Exception e){return "false";}}@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);pd2.dismiss();thanks.setText(apiData.getString("thanks.referrer.message","Thanks and we will get back to you"));thanks.setVisibility(View.VISIBLE);}}ProgressDialog pd2;@Overridepublic 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(){@Overridepublic 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> {@Overrideprotected void onPreExecute() {super.onPreExecute();}@Overrideprotected 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";}@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);Log.d("Notification Opened","Notication opened and login page");}}}