Tuesday 10 January 2017

Calling at once LocationManager

@Overridepublic void locationChanged(Location location) {
    if (location != null) {
        Log.e("Location Changed", String.valueOf(location.getLatitude()) + String.valueOf(location.getLongitude()));
        mLocation = location;
        updateMarker(mLocation);
        mLocationManager.removeListener();
    }
}

New Location Manager

package com.indiantouristplace.mapsample;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;

public class LocationManager implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<LocationSettingsResult>,
        android.location.LocationListener {

    private Activity activity;
    private LocationHandlerListener listener;
    private static LocationManager instance;
    public static final int REQUEST_CHECK_SETTINGS = 1005;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest request;
    private boolean isReqLocation;
    private LocationSettingsRequest.Builder builder;
    private PendingResult<LocationSettingsResult> result;
    private Location currentLocation;
    private android.location.LocationManager locationManager;
    private LocationSettingsRequest settingReq;
    private PendingResult<Status> requestPendingIntent;

    private LocationManager(Activity activity) {
        this.activity = activity;
    }

    public static LocationManager getInstance(Activity activity) {
        if (instance == null) {
            instance = new LocationManager(activity);
        }
        return instance;
    }

    public LocationManager buildAndConnectClient() {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(activity).addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
        }
        if (!mGoogleApiClient.isConnected()) {
            mGoogleApiClient.connect();
        }
        if (locationManager == null) {
            locationManager = (android.location.LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
            int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 0, 0, this);
            }
        }
        return this;
    }

    public LocationManager setLocationHandlerListener(LocationHandlerListener listener) {
        this.listener = listener;
        return this;
    }

    public LocationManager buildLocationRequest() {
        if (settingReq == null) {
            request = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            request.setInterval(1500);
            request.setFastestInterval(1000);
            builder = new LocationSettingsRequest.Builder().addLocationRequest(request);
            settingReq = builder.build();
        }
        return this;
    }

    public boolean requestLocation() {
        if (!mGoogleApiClient.isConnected()) {
            isReqLocation = true;
            return false;
        }
        result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, settingReq);
        result.setResultCallback(this);
        return true;
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION);
                        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                            requestPendingIntent = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, instance);
                            currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                            if (listener != null) {
                                listener.lastKnownLocationAfterConnection(currentLocation);
                            }
                        }

                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(activity, "You Must enable Location Service for app functionality", Toast.LENGTH_SHORT).show();
                        requestLocation();
                        break;
                    default:
                        break;
                }
                break;
        }
    }

    @Override    public void onLocationChanged(Location arg0) {
        if (listener != null) {
            listener.locationChanged(arg0);
            currentLocation = arg0;
        }
    }

    public void removeListener() {
        try {
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            locationManager.removeUpdates(this);
            LocationServices.FusedLocationApi.removeLocationUpdates(
                    mGoogleApiClient, instance);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public interface LocationHandlerListener {
        public void locationChanged(Location location);

        public void lastKnownLocationAfterConnection(Location location);
    }

    @Override    public void onConnected(Bundle arg0) {
        // Toast.makeText(activity, "Conn", Toast.LENGTH_SHORT).show();        if (isReqLocation) {
            requestLocation();
        }
        int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION);
        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
            currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        }
        if (listener != null) {
            listener.lastKnownLocationAfterConnection(currentLocation);
        }
    }

    @Override    public void onConnectionSuspended(int arg0) {
        // Toast.makeText(activity, "Conn Sus", Toast.LENGTH_SHORT).show();    }

    @Override    public void onConnectionFailed(ConnectionResult arg0) {
        // Toast.makeText(activity, "Conn Fail", Toast.LENGTH_SHORT).show();    }

    @Override    public void onResult(LocationSettingsResult result) {
        final Status status = result.getStatus();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                int permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION);
                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                    // Should we show an explanation?                    requestPendingIntent = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, request, instance);
                    currentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                    if (listener != null) {
                        listener.lastKnownLocationAfterConnection(currentLocation);
                    }
                }
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                try {
                    if (activity != null) {
                        status.startResolutionForResult(activity, REQUEST_CHECK_SETTINGS);
                    }
                } catch (SendIntentException e) {
                    e.printStackTrace();
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                break;
        }
    }

    public Location getCurrentLocation() {
        return currentLocation;
    }

    public void stopTracking() {
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, instance);
            mGoogleApiClient.disconnect();
        }
    }

    @Override    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override    public void onProviderEnabled(String provider) {
        if (result != null) {
            result.cancel();
        }

    }

    @Override    public void onProviderDisabled(String provider) {
        if (result != null) {
            result.cancel();
            requestLocation();
        }
    }
}

Tuesday 29 November 2016

BaseAdapter

public class RecipeListApapter extends BaseAdapter {

Context context;
LayoutInflater inflater;
List<RecipeBean> recipes;
OnRecipeClickListener onRecipeClickListener;
ImageLoaderListner imageLoaderListner;


public RecipeListApapter(Context context, List<RecipeBean> recipes, OnRecipeClickListener onRecipeClickListener) {

this.context = context;
this.recipes = recipes;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.onRecipeClickListener=onRecipeClickListener;
imageLoaderListner = (ImageLoaderListner)context;

}

@Override
public int getCount() {
return recipes.size();
}

@Override
public RecipeBean getItem(int position) {
return recipes.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

//int idofimage = -1;

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.recipe_item, null);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
initView(position, holder, convertView);
RecipeBean recipe = recipes.get(position);
setView(holder, recipe);
return convertView;
}

private void setView(ViewHolder holder, RecipeBean recipe) {
//idofimage = Comman.getImageResourceId(context, recipe.getRecipeImage());
holder.txt_recipetitle.setText(recipe.getRecipeName());
holder.txt_recipetime.setText(recipe.getRecipetime());
//holder.img_recipe.setImageResource(idofimage);

/* Picasso.with(context).load(recipe.getRecipeUrl())
.into(holder.img_recipe);*/

imageLoaderListner.onImageLoad(recipe.getRecipeUrl(), holder.img_recipe, R.drawable.ic_launcher);

if(recipe.getIsFavourites()==1){
holder.likeTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_selected, 0, 0, 0);
}else
{
holder.likeTxt.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like, 0, 0, 0);
}
}

private void initView(final int position, ViewHolder holder, View convertView) {
holder.layoutRateLike = (LinearLayout) convertView
.findViewById(R.id.layoutRateLike);
holder.layouRate = (LinearLayout)convertView.findViewById(R.id.layouRate);
holder.layoutLike = (LinearLayout)convertView.findViewById(R.id.layoutLike);
holder.lineView = (View)convertView.findViewById(R.id.lineView);

holder.layoutRateLike.setVisibility(View.VISIBLE);
holder.layouRate.setVisibility(View.GONE);
holder.lineView.setVisibility(View.GONE);

holder.img_recipe = (ImageView) convertView
.findViewById(R.id.img_recipe);
holder.txt_recipetitle = (TextView) convertView
.findViewById(R.id.txt_recipetitle);
holder.txt_recipetime = (TextView) convertView
.findViewById(R.id.txt_recipetime);
holder.likeTxt = (TextView) convertView.findViewById(R.id.likeTxt);

holder.layoutLike.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
if (onRecipeClickListener != null) {
onRecipeClickListener.onLikeClick(v, position);
}

}
});
}

static class ViewHolder {
ImageView img_recipe;
TextView txt_recipetitle, txt_recipetime, likeTxt;
LinearLayout layoutRateLike, layoutLike, layouRate;
View lineView;
}

public interface OnRecipeClickListener {
void onLikeClick(View view, int position);
}

/*private class ImageLoadTask extends AsyncTask<Void, Void, Integer> {

String imgName;
ImageView imageView;

public ImageLoadTask(String imgName, ImageView imageView) {
this.imgName = imgName;
this.imageView = imageView;
}

@Override
protected Integer doInBackground(Void... params) {
// TODO Auto-generated method stub

int imgId = context.getResources().getIdentifier(imgName,
"drawable", context.getPackageName());

return imgId;
}

@Override
protected void onPostExecute(Integer imgResId) {
// TODO Auto-generated method stub
super.onPostExecute(imgResId);

imageView.setImageResource(imgResId);
}

}*/

}

Card Adapter

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

// List<MenuItem> mItems;

OnItemClickListener mItemClickListener;
Context context;
List<CategoryBean> catItems;
int defaultImgId;
ImageLoaderListner imageLoaderListner;

public CardAdapter(Context context, List<CategoryBean> catItems, int defaultImgId) {

this.context = context;
this.catItems = catItems;
this.defaultImgId=defaultImgId;
imageLoaderListner = (ImageLoaderListner)context;
}

class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {

public LinearLayout placeHolder;
public LinearLayout placeNameHolder;
public ImageView img_categories;
public TextView txt_categories;

public ViewHolder(View itemView) {
super(itemView);
placeHolder = (LinearLayout) itemView.findViewById(R.id.mainHolder);
placeNameHolder = (LinearLayout) itemView
.findViewById(R.id.placeNameHolder);
// lin_categories =
// (RelativeLayout)itemView.findViewById(R.id.lin_categories);
img_categories = (ImageView) itemView
.findViewById(R.id.img_categories);
txt_categories = (TextView) itemView
.findViewById(R.id.txt_categories);

placeHolder.setOnClickListener(this);
}

@Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(itemView, getAdapterPosition());
}

}

}

public interface OnItemClickListener {
void onItemClick(View view, int position);
}

public void setOnItemClickListener(
final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}

@Override
public int getItemCount() {
// TODO Auto-generated method stub
return catItems.size();
}

@SuppressWarnings("deprecation")
@Override
public void onBindViewHolder(final ViewHolder holder, final int i) {
CategoryBean mItem = catItems.get(i);
Log.e("OnBind..", ""+i);
imageLoaderListner.onImageLoad(mItem.getCatImgNameResourceId(context), holder.img_categories, defaultImgId);
//holder.img_categories.setImageResource(mItem.getCatImgNameResourceId(context));
holder.txt_categories.setText(mItem.getCatName());
holder.placeNameHolder.setBackgroundColor(mItem.getmColor());

/*Bitmap myPhoto = BitmapFactory.decodeResource(context.getResources(),
mItem.getCatImgNameResourceId(context));
Palette.generateAsync(myPhoto, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
int bgColor = palette.getVibrantColor(context
.getResources().getColor(android.R.color.black));
Log.e("color code"+i, bgColor+"");
holder.placeNameHolder.setBackgroundColor(bgColor);
}
});*/

holder.placeNameHolder.setAlpha(0.8f);

}

//private ViewHolder viewHolder;
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
// TODO Auto-generated method stub
View v = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.recycler_view_card_item, viewGroup, false);
Log.e("onCreateViewHolder..", ""+i);

ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}

}

Implementing LocationManager to Activity


implements LocationManager.LocationHandlerListener
and then calling...... onCreate();
locationManager = LocationManager.getInstance(activity).setLocationHandlerListener(HomeActivity.this).buildAndConnectClient().buildLocationRequest();
        locationManager.requestLocation();




@Override
    public void locationChanged(Location location) {
        if (location != null) {
            Log.e("lat " + location.getLatitude(), "lon " + location.getLongitude());
            isLocationFinded = true;
//            latLng = Helper.formattedLatLong(new LatLng(location.getLatitude(), location.getLongitude()));
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
//            location.setLatitude(latLng.latitude);
//            location.setLongitude(latLng.longitude);
            if (latLngUserSelected == null) {
                latLngUserSelected = latLng;
            }
            if (locationListener != null) {
                locationListener.update(location);
            }
            if (oneTime) {
                latlngJsonObject = new JsonObject();
                latlngJsonObject.addProperty(Const.USERID, user_id);
                latlngJsonObject.addProperty("latLong", latLng.latitude + "," + latLng.longitude);
                isOfferer = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.IS_OFFERER, "");
                latlngJsonObject.addProperty(Const.IS_OFFERER, isOfferer);
                updateLocationToServer();
            }
            if (true) {//isShareLocation
                latlngJsonObject = new JsonObject();
                latlngJsonObject.addProperty(Const.USERID, user_id);
                latlngJsonObject.addProperty("latLong", latLng.latitude + "," + latLng.longitude);
                isOfferer = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.IS_OFFERER, "");
                latlngJsonObject.addProperty(Const.IS_OFFERER, isOfferer);
                updateLocationToServer();
            }
        }
    }

    @Override
    public void lastKnownLocationAfterConnection(Location location) {
        if (location != null) {
//            latLng = Helper.formattedLatLong(new LatLng(location.getLatitude(), location.getLongitude()));
        }
    }

    private void updateLocationToServer() {
        if (Helper.isConnected(activity)) {

            Log.e("json", latlngJsonObject.toString());
            Ion.with(activity)
                    .load(API.API_UPDATE_LATLNG)
                    .setJsonObjectBody(latlngJsonObject)
                    .asString()
                    .setCallback(new FutureCallback<String>() {

                        @Override
                        public void onCompleted(Exception e, String jsonString) {
//                            JSONObject jsonObject = null;
//                            try {
//                                jsonObject = new JSONObject(jsonString);
//                                if (jsonObject.optBoolean(Const.IS_SUCCESS)) {
                            oneTime = false;
//                                }
//                            } catch (Exception e1) {
//                                e1.printStackTrace();
//                            }

                        }
                    });
        }
    }


    private Runnable autoCancelLocationRunnable = new Runnable() {

        @Override
        public void run() {
            isShareLocation = false;
            sharedPreference.putBoolean("shareLocation", false);
        }
    };

    public void setRequesterStatus(String id) {
        statusHashMap.put(id, "2");
        isStatusEnd = true;
        progress.show();
    }


####################################################################

package com.liftindia.app.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.liftindia.app.DirectionsJSONParserDistance;
import com.liftindia.app.bean.DataBeanTypeOne;
import com.liftindia.app.bean.PaymentDueBean;
import com.liftindia.app.bean.SearchLiftBean;
import com.liftindia.app.bean.TrackerBean;
import com.liftindia.app.bean.FavoriteBean;
import com.liftindia.app.bean.LiftBean;
import com.liftindia.app.bean.OfferedListBean;
import com.liftindia.app.bean.RequestedListBean;
import com.liftindia.app.bean.RideStartBean;
import com.liftindia.app.bean.VehicleBean;
import com.liftindia.app.firebase.ChatActivity;
import com.liftindia.app.firebase.ChatFragment;
import com.liftindia.app.firebase.FireConst;
import com.liftindia.app.fragment.ContactUsFragment;
import com.liftindia.app.fragment.EndLiftFragment;
import com.liftindia.app.fragment.FaqFragment;
import com.liftindia.app.fragment.HistoryFragment;
import com.liftindia.app.fragment.HowFragment;
import com.liftindia.app.fragment.LiftDetailsFragment;
import com.liftindia.app.fragment.PendingOfferFragment;
import com.liftindia.app.fragment.TrackerUserFragment;
import com.liftindia.app.fragment.ViewInAppFragment;
import com.liftindia.app.fragment.PaymentDetailsFragment;
import com.liftindia.app.fragment.WalletFragment;
import com.liftindia.app.fragment.PendingLiftListFragment;
import com.liftindia.app.fragment.ProfileFragment;
import com.liftindia.app.fragment.RequestedLiftDetailsFragment;
import com.liftindia.app.fragment.TrackerFragment;
import com.liftindia.app.gcm.FirebaseNotificationService;
import com.liftindia.app.helper.API;
import com.liftindia.app.helper.Const;
import com.liftindia.app.helper.DbAdapter;
import com.liftindia.app.helper.LocationManager;
import com.liftindia.app.fragment.OfferLiftFragment;
import com.liftindia.app.fragment.RequestLiftFragment;
import com.liftindia.app.fragment.SearchLiftFragment;
import com.liftindia.app.fragment.SendRequestFragment;
import com.liftindia.app.helper.Helper;
import com.liftindia.app.R;
import com.liftindia.app.fragment.HomeFragment;
import com.liftindia.app.helper.Progress;
import com.liftindia.app.helper.SharedPreference;
import com.liftindia.app.helper.SmsReceiver;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import at.grabner.circleprogress.CircleProgressView;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

public class HomeActivity extends BaseActivity implements LocationManager.LocationHandlerListener, FragmentManager.OnBackStackChangedListener, ChildEventListener, SmsReceiver.OnSmsReceived {
    Activity activity;
    public Progress progress;
    JsonObject jsonObject;
    JsonObject latlngJsonObject;
    private Firebase mFire;
    DataBeanTypeOne dataBeanTypeOne;
    int listSize = 0, count = 0;

    public Dialog dialog;

    public LinearLayout linearParent;
    long backPressed = 0l;
    LocationManager locationManager;
    public static LatLng latLng = null;
    public static LatLng latLngUserSelected = null;
    public static boolean isReceiverRegistered = false;
    private PushBroadcastReceiver receiver;
    private IntentFilter intentFilter;
    private Intent pushIntent;

    public static String favStartId = "", favEndId = "";
    String isOfferer = "";
    public boolean isLocationFinded = false;
    public boolean isLocatingCurrentPosition = false;
    boolean isRequesterAdded = false;
    boolean isStatusEnd = false;
    public HashMap<String, String> distanceHashMap = new HashMap<>();
    public HashMap<String, String> statusHashMap = new HashMap<>();
    public HashMap<String, String> pickPointHashMap = new HashMap<>();


    //    public static HashMap<String, List<FavoriteBean>> favBeanStringListHashMap;
    public static List<FavoriteBean> favBeanStringList;

    public String user_id = "";
    public String userId = "";
    public String name = "";
    public String age = "";
    public String fbFriends = "";
    public String reviews = "";
    public String rating = "0";
    public String mobile = "";
    public String designation = "";
    public String connections = "";
    public String vehicleNo = "";
    public String carName = "";
    public String carDetails = "";
    public String type = "";
    public String pickPoints = "";
    public String dropPoint = "";
    public String startPoints = "";
    public String profileImage = "";
    public String imageUrl = "";
    public String pickAddress = "";
    public String dropAddress = "";
    public String eta = "";
    public String rate = "";
    public String lastLocationLatlng = "";

    public String liftId = "";
    public String offererId = "";
    public String requesterId = "";
    public String action = "";

    public LatLng pick;
    public LatLng drop;
    public LatLng start;
    long autoCancelRequestTime = 0l;
    SharedPreference sharedPreference;

    AlertDialog alertDialog;
    boolean isStarted = false;
    boolean oneTime = true;
    public static boolean isShareLocation = false;
    public static boolean isLiftRequestFragmentVisible = false;

    TextView tv_pickup_location;
    TextView tv_drop_location;
    TextView tv_eta;
//    RatingBar ratingBar;
//    ImageView star1;
//    ImageView star2;
//    ImageView star3;

    private Handler autoLocationCancelHandler = new Handler();
    public Handler networkHitHandler = new Handler();

    public static List<VehicleBean> vehicleList = new ArrayList<>();
    public GetLocationUpdate locationListener;
    public UpdateTracker updateTracker;
    RideStartBean rideStartBean;
    private Firebase firebase;
    public static ArrayList<TrackerBean> trackerBeanArrayList = new ArrayList<>();
    TrackerFragment trackerFragment;
    private boolean isRequestDialogShowing = false;
    private boolean isConfirmedDialogShowing = false;

    public String payBy = "";
    private AlertDialog helpDialog;
    private int sec = 0;
    CircleProgressView circleProgressView;
    Timer timer;

    String contact_no = "", police = "100";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Firebase.setAndroidContext(this);
        activity = this;
        progress = new Progress(activity);
        startService(new Intent(activity, FirebaseNotificationService.class));

        linearParent = (LinearLayout) findViewById(R.id.linearParent);
        locationManager = LocationManager.getInstance(activity).setLocationHandlerListener(HomeActivity.this).buildAndConnectClient().buildLocationRequest();
        locationManager.requestLocation();

        user_id = Const.getUserId(activity);

        if (Helper.isConnected(activity)) {
            createFirebaseData();
        }

        receiver = new PushBroadcastReceiver();
        pushIntent = getIntent();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Const.ACTION_PUSH);
        intentFilter.setPriority(999);

        HomeFragment homeFragment = HomeFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, homeFragment).addToBackStack(null).commit();

        checkAppStatus();


        if (pushIntent.hasExtra("msg")) {
            try {
                dataBeanTypeOne = (DataBeanTypeOne) pushIntent.getSerializableExtra("msg");
//                dataBeanTypeOne = fireBean.dataBeanTypeOne;
                onFirebaseMessageReceived(dataBeanTypeOne.pushType);
//                String jsonString = pushIntent.getStringExtra("msg");
//                onPushReceived(jsonString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (getIntent().hasExtra(Const.GOTO)) {
            if (getIntent().getStringExtra(Const.GOTO).equalsIgnoreCase("RequestLiftFragment")) {
                RequestLiftFragment requestLiftFragment = RequestLiftFragment.newInstance();
                getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, requestLiftFragment).commit();
            }
        }
/*
        mFire = new Firebase(FireConst.FIREBASE_URL + "/" + FireConst.PUSH_DATA + "/" + user_id);
        mFire.child(FireConst.TYPE1).addChildEventListener(this);
        mFire.child(FireConst.TYPE2).addChildEventListener(this);
        mFire.child(FireConst.TYPE3).addChildEventListener(this);
        mFire.child(FireConst.TYPE5).addChildEventListener(this);
        mFire.child(FireConst.TYPE6).addChildEventListener(this);
        mFire.child(FireConst.TYPE7).addChildEventListener(this);
        mFire.child(FireConst.TYPE8).addChildEventListener(this);
        mFire.child(FireConst.TYPE10).addChildEventListener(this);
        mFire.child(FireConst.TYPE20).addChildEventListener(this);
        mFire.child(FireConst.TYPE11).addChildEventListener(this);
        mFire.child(FireConst.CHAT).addChildEventListener(this);*/
    }

    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
        if (dataSnapshot != null && dataSnapshot.getValue() != null) {
            dataBeanTypeOne = dataSnapshot.getValue(DataBeanTypeOne.class);
            String type = dataBeanTypeOne.pushType;
            String user = dataBeanTypeOne.userId;
            mFire.child(type).child(user).removeValue();
            onFirebaseMessageReceived(type);
        }
    }

    @Override
    public void onChildChanged(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onChildRemoved(DataSnapshot dataSnapshot) {

    }

    @Override
    public void onChildMoved(DataSnapshot dataSnapshot, String s) {

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {

    }


    public void onFirebaseMessageReceived(String pushType) {
        Log.e("pushType", pushType);
        try {
            if (pushType != null) {
                sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
                String pushMessage = "";
                switch (pushType) {
                    case "type1"://Lift Request R2O
                        liftId = dataBeanTypeOne.liftId;
                        name = dataBeanTypeOne.name;
                        imageUrl = dataBeanTypeOne.profileImage;
                        if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("https")) {
                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("https:"));
                        } else if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("http")) {
                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("http:"));
                        }
                        age = dataBeanTypeOne.age;
                        fbFriends = dataBeanTypeOne.fbFriends;
                        reviews = dataBeanTypeOne.reviews;
                        rating = dataBeanTypeOne.rating;
                        mobile = dataBeanTypeOne.mobile;
                        designation = dataBeanTypeOne.designation;
                        userId = dataBeanTypeOne.userId;
                        requesterId = dataBeanTypeOne.userId;
                        connections = dataBeanTypeOne.connections;
                        pickPoints = dataBeanTypeOne.pickPoints;
                        pick = new LatLng(Double.parseDouble(pickPoints.split(",")[0]), Double.parseDouble(pickPoints.split(",")[1]));
                        getSource(pick);
                        dropPoint = dataBeanTypeOne.dropPoint;
                        drop = new LatLng(Double.parseDouble(dropPoint.split(",")[0]), Double.parseDouble(dropPoint.split(",")[1]));
                        startPoints = dataBeanTypeOne.startPoint;
                        start = new LatLng(Double.parseDouble(startPoints.split(",")[0]), Double.parseDouble(startPoints.split(",")[1]));
                        getDestination(drop);
                        saveRequesterDetails();
                        sharedPreference.putInt(Const.GOTO, Const.TYPE1);
                        requestDialog();
                        break;

                    case "20": //R2O
                        liftId = dataBeanTypeOne.liftId;
                        offererId = dataBeanTypeOne.userId;
                        requesterId = Const.getUserId(activity);
                        action = "1";
                        if (validate()) {
                            networkHit();
                        }
                        break;
                    case "type3"://Request Rejected O2R
                        sharedPreference.putInt(Const.GOTO, Const.TYPE3);
                        pushMessage = dataBeanTypeOne.pushMessage;
                        msgDialog(pushMessage);
                        sharedPreference.putString(Const.TYPE3 + "", pushMessage);
//                            Your request for " Start point " to " End Point" is rejected by the " Offerer Name"
                        break;
                    case "type5"://Lift Request cancelled by the requester. R2O
                        sharedPreference.putInt(Const.GOTO, Const.TYPE5);
                        pushMessage = dataBeanTypeOne.pushMessage;
                        msgDialog(pushMessage);
                        sharedPreference.putString(Const.TYPE5 + "", pushMessage);
                        break;
                    case "type6"://Lift Started R2O
                        sharedPreference.putInt(Const.GOTO, Const.TYPE6);
                        pushMessage = dataBeanTypeOne.pushMessage;
                        msgDialog(pushMessage);
                        sharedPreference.putString(Const.TYPE6 + "", pushMessage);
                        break;
                    case "10":
                        name = dataBeanTypeOne.name;
                        age = dataBeanTypeOne.age;
                        eta = dataBeanTypeOne.eta;
                        mobile = dataBeanTypeOne.mobile;
                        userId = dataBeanTypeOne.userId;
                        updateETA();
                        break;

                    case "type11":
//                        updateTracker.updateLocationOnMap(jsonObject);
                        break;
                    case "chat":
                        String chatUser = dataBeanTypeOne.senderId;
                        Intent intent = new Intent(activity, ChatActivity.class);
                        intent.putExtra(FireConst.CHAT_WITH_USER, chatUser);
                        startActivity(intent);
                        break;
                    case "msgUser":
                    case "msgVehicle":
                        pushMessage = dataBeanTypeOne.pushMessage;
                        msgDialog(pushMessage);
                        break;
                }
            }

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

    public void createFirebaseData() {
        firebase = new Firebase(FireConst.FIREBASE_URL);
        SharedPreference pref = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
        firebase.child(FireConst.USER_DATA).child(pref.getString(FireConst.USER_ID, "")).child(FireConst.NAME).setValue(pref.getString(FireConst.NAME, ""));
        firebase.child(FireConst.USER_DATA).child(pref.getString(FireConst.USER_ID, "")).child(FireConst.PROFILE_IMAGE).setValue(pref.getString(FireConst.PROFILE_IMAGE, ""));
    }


    private void checkAppStatus() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
        int goTo = sharedPreference.getInt(Const.GOTO, 0);
        switch (goTo) {
            case Const.TYPE1:
                getRequesterDetails();
                requestDialog();
                break;
            case Const.TYPE2:
                getOffererDetails();
                confirmedDialog();
                break;
            case Const.TYPE3:
//                getOffererDetails();
                msgDialog(sharedPreference.getString(Const.TYPE3 + "", ""));
                break;
            case Const.TYPE5:
//                getRequesterDetails();
                msgDialog(sharedPreference.getString(Const.TYPE5 + "", ""));
                break;
            case Const.TYPE6:
                msgDialog(sharedPreference.getString(Const.TYPE6 + "", ""));
                break;
            case Const.TYPE7:
//                msgDialog("Ride Stopped", "Ride is stopped by the requester.");
                break;
            case Const.END_LIFT:
                getOffererDetails();
                createRideStartBean();
                gotoEndLiftFragment();
                break;
            case Const.PAYMENT_DUE:
                getOffererDetails();
                createRideStartBean();
                gotoEndLiftFragment();
                createPaymentDueBean();

                break;
        }
        isShareLocation = sharedPreference.getBoolean("shareLocation", false);
//        if (isShareLocation) {
//            //autoCancelLocationUpdateIfNoLiftRequest();
//        }
    }

    private void createPaymentDueBean() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_DUE_PAYMENT_DETAILS);
        PaymentDueBean bean = PaymentDueBean.newInstance();
        bean.liftId = sharedPreference.getString(Const.LIFT_ID, "");
        bean.offererId = sharedPreference.getString(Const.OFFERER_ID, "");
        bean.mobile = sharedPreference.getString(Const.MOBILE, "");
        bean.email = sharedPreference.getString(Const.EMAIL, "");
        bean.amount = Float.parseFloat(sharedPreference.getString(Const.AMOUNT, "0.0"));
        bean.distance = Float.parseFloat(sharedPreference.getString(Const.DISTANCE, "0.0"));
        bean.timeTaken = sharedPreference.getLong(Const.TIME_TAKEN, 0l);
    }


    public void updateProfileImages(String url) {
        menuFrag.updateLeftMenuImages(url);
    }

    @Override
    public void onBackPressed() {
        Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (BaseActivity.mDrawer.isMenuVisible()) {
            BaseActivity.mDrawer.closeMenu();
        } else if (visibleFragment instanceof HomeFragment) {
            if (backPressed + 2000 > System.currentTimeMillis()) {
                finish();
            } else {
                backPressed = System.currentTimeMillis();
                Helper.showSnackBar(linearParent, "Press once again to Exit");
            }
        } else if (visibleFragment instanceof ViewInAppFragment) {

        } else if ((visibleFragment instanceof PendingLiftListFragment) ||
                (visibleFragment instanceof HowFragment) ||
                (visibleFragment instanceof FaqFragment) ||
                (visibleFragment instanceof ChatFragment) ||
                (visibleFragment instanceof ContactUsFragment) ||
                (visibleFragment instanceof ProfileFragment) ||
                (visibleFragment instanceof SearchLiftFragment) ||
                (visibleFragment instanceof OfferLiftFragment) ||
                (visibleFragment instanceof RequestLiftFragment) ||
                (visibleFragment instanceof HistoryFragment) ||
                (visibleFragment instanceof PaymentDetailsFragment) ||
                (visibleFragment instanceof WalletFragment)) {
            isLiftRequestFragmentVisible = false;
            clearBackStack();
            HomeFragment homeFragment = HomeFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, homeFragment).commit();
        } else if (getSupportFragmentManager().getBackStackEntryCount() >= 1) {
            getSupportFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }


    public void go2Home() {
        Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (visibleFragment instanceof SendRequestFragment) {
            ((SendRequestFragment) visibleFragment).rl_offer_list.setVisibility(View.GONE);
        }
        clearBackStack();
        HomeFragment homeFragment = HomeFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, homeFragment).commit();
    }

    // CLEAR BACK STACK.
    private void clearBackStack() {
        final FragmentManager fragmentManager = getSupportFragmentManager();
//        while (fragmentManager.getBackStackEntryCount() != 0) {
//            fragmentManager.popBackStackImmediate();
        fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (fragment instanceof ProfileFragment) {
            ((ProfileFragment) fragment).onActivityResult(requestCode, resultCode, data);
        }
        if (fragment instanceof HomeFragment) {
            ((HomeFragment) fragment).onActivityResult(requestCode, resultCode, data);
        }
        if (fragment instanceof EndLiftFragment) {
            ((EndLiftFragment) fragment).onActivityResult(requestCode, resultCode, data);
        }
        locationManager.onActivityResult(requestCode, resultCode, data);

        // bug fix mayank
        // home fragment already call and marker is already set so when user give permission for GPS map and marker are already set
        // here we check if req code is = loction per req code then reload the fragment

        if (requestCode == 1005) {
            HomeFragment homeFragment = HomeFragment.newInstance();
            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, homeFragment).addToBackStack(null).commit();
        }

    }


    public void gotoWalletFragment() {
        WalletFragment walletFragment = WalletFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, walletFragment).commit();
    }

    public void gotoTrackerUserFragment() {
        TrackerUserFragment trackerUserFragment = TrackerUserFragment.newInstance();
        getSupportFragmentManager().beginTransaction().add(R.id.frag_container, trackerUserFragment).addToBackStack("trackerUserFragment").commit();
    }

    public void gotoOfferLiftFragment(String vehicleId, String vehicleType) {
        OfferLiftFragment offerLiftFragment = OfferLiftFragment.newInstance(vehicleId, vehicleType);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, offerLiftFragment).commit();
        isLocationFinded = false;
        isLocatingCurrentPosition = false;
    }

    public void gotoRequestLiftFragment() {
        RequestLiftFragment requestLiftFragment = RequestLiftFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, requestLiftFragment).commit();
        isLocationFinded = false;
        isLocatingCurrentPosition = false;
    }

    public void gotoTrackerFragment() {
        TrackerFragment trackerFragment = TrackerFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, trackerFragment).commit();
    }

    public void gotoSearchLiftFragment(ArrayList<LiftBean> liftBeanArrayList, SearchLiftBean searchLiftBean) {
        SearchLiftFragment searchLiftFragment = SearchLiftFragment.newInstance(liftBeanArrayList, searchLiftBean);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, searchLiftFragment).commit();
    }

    public void gotoSendRequestLiftFragment(ArrayList<LiftBean> liftBeanArrayList, int position, SearchLiftBean searchLiftBean) {
        SendRequestFragment sendRequestFragment = SendRequestFragment.newInstance(liftBeanArrayList, position, searchLiftBean);
        getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.in_left, R.anim.out_right, R.anim.in_right, R.anim.out_left).replace(R.id.frag_container, sendRequestFragment).addToBackStack("SendRequest").commit();
    }

    public void replaceBillingDetailsFragment(ArrayList<OfferedListBean> dataList, int position) {
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, LiftDetailsFragment.newInstance(dataList, position)).addToBackStack("LiftDetailsFragment").commit();
    }

    public void replaceLifterBillingDetailsFragment(ArrayList<RequestedListBean> dataList, int position) {
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, RequestedLiftDetailsFragment.newInstance(dataList, position)).addToBackStack("RequestedLiftDetailsFragment").commit();
    }

    public void gotoEndLiftFragment() {
        EndLiftFragment endLiftFragment = EndLiftFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, endLiftFragment).commit();
    }

    public void gotoPaymentDetailsFragment() {
        PaymentDetailsFragment paymentDeatails = PaymentDetailsFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, paymentDeatails).commit();
    }

    public void gotoLiftRequestFragment() {
        ViewInAppFragment viewInAppFragment = ViewInAppFragment.newInstance();
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, viewInAppFragment).commit();
        isLiftRequestFragmentVisible = true;
    }

    public void setAddressInLiftRequestFragment() {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (fragment instanceof ViewInAppFragment) {
            ((ViewInAppFragment) fragment).setAddress();
        }
    }

    public void unFavourite(boolean isStart) {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (fragment instanceof OfferLiftFragment) {
            ((OfferLiftFragment) fragment).unFavourite(isStart);
        }
        if (fragment instanceof RequestLiftFragment) {
            ((RequestLiftFragment) fragment).unFavourite(isStart);
        }
        if (fragment instanceof PendingOfferFragment) {
            ((PendingOfferFragment) fragment).unFavourite(isStart);
        }
    }
//    public void gotoOffererProfileFragment(ArrayList<LiftBean> liftBeanArrayList, int position) {
//        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
//        OffererProfileActivity offererProfileFragment = OffererProfileActivity.newInstance(liftBeanArrayList, position);
//        if (fragment instanceof HomeFragment) {
//            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, offererProfileFragment).addToBackStack("offererProfileFragment").commit();
//        } else {
//            getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, offererProfileFragment).commit();
//        }
//    }

    public void gotoPendingRequestFragment(boolean isEdit, boolean isOffer) {
        PendingOfferFragment pendingOfferFragment = PendingOfferFragment.newInstance();
        Bundle bundle = new Bundle();
        bundle.putBoolean("isEdit", isEdit);
        bundle.putBoolean("isOffer", isOffer);
        pendingOfferFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_container, pendingOfferFragment).addToBackStack(null).commit();
    }

    @Override
    public void locationChanged(Location location) {
        if (location != null) {
            Log.e("lat " + location.getLatitude(), "lon " + location.getLongitude());
            isLocationFinded = true;
//            latLng = Helper.formattedLatLong(new LatLng(location.getLatitude(), location.getLongitude()));
            latLng = new LatLng(location.getLatitude(), location.getLongitude());
//            location.setLatitude(latLng.latitude);
//            location.setLongitude(latLng.longitude);
            if (latLngUserSelected == null) {
                latLngUserSelected = latLng;
            }
            if (locationListener != null) {
                locationListener.update(location);
            }
            if (oneTime) {
                latlngJsonObject = new JsonObject();
                latlngJsonObject.addProperty(Const.USERID, user_id);
                latlngJsonObject.addProperty("latLong", latLng.latitude + "," + latLng.longitude);
                isOfferer = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.IS_OFFERER, "");
                latlngJsonObject.addProperty(Const.IS_OFFERER, isOfferer);
                updateLocationToServer();
            }
            if (true) {//isShareLocation
                latlngJsonObject = new JsonObject();
                latlngJsonObject.addProperty(Const.USERID, user_id);
                latlngJsonObject.addProperty("latLong", latLng.latitude + "," + latLng.longitude);
                isOfferer = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.IS_OFFERER, "");
                latlngJsonObject.addProperty(Const.IS_OFFERER, isOfferer);
                updateLocationToServer();
            }
        }
    }

    @Override
    public void lastKnownLocationAfterConnection(Location location) {
        if (location != null) {
//            latLng = Helper.formattedLatLong(new LatLng(location.getLatitude(), location.getLongitude()));
        }
    }

    private void updateLocationToServer() {
        if (Helper.isConnected(activity)) {

            Log.e("json", latlngJsonObject.toString());
            Ion.with(activity)
                    .load(API.API_UPDATE_LATLNG)
                    .setJsonObjectBody(latlngJsonObject)
                    .asString()
                    .setCallback(new FutureCallback<String>() {

                        @Override
                        public void onCompleted(Exception e, String jsonString) {
//                            JSONObject jsonObject = null;
//                            try {
//                                jsonObject = new JSONObject(jsonString);
//                                if (jsonObject.optBoolean(Const.IS_SUCCESS)) {
                            oneTime = false;
//                                }
//                            } catch (Exception e1) {
//                                e1.printStackTrace();
//                            }

                        }
                    });
        }
    }


    private Runnable autoCancelLocationRunnable = new Runnable() {

        @Override
        public void run() {
            isShareLocation = false;
            sharedPreference.putBoolean("shareLocation", false);
        }
    };

    public void setRequesterStatus(String id) {
        statusHashMap.put(id, "2");
        isStatusEnd = true;
        progress.show();
    }

    @Override
    public void onBackStackChanged() {
        Fragment frag = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (frag instanceof HomeFragment) {

        }
    }

    @Override
    public void onParseCompleted(String otp) {
        Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
        if (visibleFragment instanceof WalletFragment) {
            ((WalletFragment) visibleFragment).onParseCompleted(otp);
        }
    }


    public class PushBroadcastReceiver extends android.content.BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("In Broadcast Receiver", "In Broadcast Receiver");
            try {
//                Bundle extras = intent.getExtras();
//                String jsonString = extras.getString("msg");
                dataBeanTypeOne = (DataBeanTypeOne) intent.getSerializableExtra("msg");
//                dataBeanTypeOne = fireBean.dataBeanTypeOne;
                onFirebaseMessageReceived(dataBeanTypeOne.pushType);
//                onPushReceived(jsonString);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void saveRequesterDetails() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_REQUESTER_DETAILS);
        sharedPreference.putString(Const.LIFT_ID, liftId);
        sharedPreference.putString(Const.NAME, name);
        sharedPreference.putString(Const.AGE, age);
        sharedPreference.putString(Const.FB_FRIENDS, fbFriends);
        sharedPreference.putString(Const.REVIEWS, reviews);
        sharedPreference.putString(Const.MOBILE, mobile);
        sharedPreference.putString(Const.DESIGNATION, designation);
        sharedPreference.putString(Const.USERID, userId);
        sharedPreference.putString(Const.REQUESTER_ID, requesterId);
        sharedPreference.putString(Const.CONNECTIONS, connections);
        sharedPreference.putString(Const.PICK_POINTS, pickPoints);
        sharedPreference.putString(Const.DROP_POINT, dropPoint);
    }

    private void getRequesterDetails() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_REQUESTER_DETAILS);
        liftId = sharedPreference.getString(Const.LIFT_ID, "");
        name = sharedPreference.getString(Const.NAME, "");
        age = sharedPreference.getString(Const.AGE, "");
        fbFriends = sharedPreference.getString(Const.FB_FRIENDS, "");
        reviews = sharedPreference.getString(Const.REVIEWS, "");
        mobile = sharedPreference.getString(Const.MOBILE, "");
        designation = sharedPreference.getString(Const.DESIGNATION, "");
        userId = sharedPreference.getString(Const.USERID, "");
        requesterId = sharedPreference.getString(Const.REQUESTER_ID, "");
        connections = sharedPreference.getString(Const.CONNECTIONS, "");
        pickPoints = sharedPreference.getString(Const.PICK_POINTS, "");
        dropPoint = sharedPreference.getString(Const.DROP_POINT, "");
        pick = new LatLng(Double.parseDouble(pickPoints.split(",")[0]), Double.parseDouble(pickPoints.split(",")[1]));
        getSource(pick);
        drop = new LatLng(Double.parseDouble(dropPoint.split(",")[0]), Double.parseDouble(dropPoint.split(",")[1]));
        getDestination(drop);
    }

    private void saveOffererDetails() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS);
        sharedPreference.putString(Const.LIFT_ID, liftId);
        sharedPreference.putString(Const.NAME, name);
        sharedPreference.putString(Const.IMAGE_URL, imageUrl);
        sharedPreference.putString(Const.AGE, age);
        sharedPreference.putString(Const.VEHICLE_NUMBER, vehicleNo);
        sharedPreference.putString(Const.REVIEWS, reviews);
        sharedPreference.putString(Const.RATING, rating);
        sharedPreference.putString(Const.MOBILE, mobile);
        sharedPreference.putString(Const.CAR_NAME, carName);
        sharedPreference.putString(Const.CAR_DETAILS, carDetails);
        sharedPreference.putString(Const.USERID, userId);
        sharedPreference.putString(Const.OFFERER_ID, offererId);
        sharedPreference.putString(Const.TYPE, type);
        sharedPreference.putString(Const.PICK_POINTS, pickPoints);
        sharedPreference.putString(Const.DROP_POINT, dropPoint);
        sharedPreference.putString("lastLocationLatlng", "");
    }

    private void getOffererDetails() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS);
        liftId = sharedPreference.getString(Const.LIFT_ID, "");
        name = sharedPreference.getString(Const.NAME, "");
        imageUrl = sharedPreference.getString(Const.IMAGE_URL, "");
        age = sharedPreference.getString(Const.AGE, "");
        vehicleNo = sharedPreference.getString(Const.VEHICLE_NUMBER, "");
        reviews = sharedPreference.getString(Const.REVIEWS, "");
        rating = sharedPreference.getString(Const.RATING, "0");
        mobile = sharedPreference.getString(Const.MOBILE, "");
        carName = sharedPreference.getString(Const.CAR_NAME, "");
        carDetails = sharedPreference.getString(Const.CAR_DETAILS, "");
        userId = sharedPreference.getString(Const.USERID, "");
        offererId = sharedPreference.getString(Const.OFFERER_ID, "");
        requesterId = Const.getUserId(activity);
        type = sharedPreference.getString(Const.TYPE, "");
        rate = sharedPreference.getString(Const.RATE, "");
        pickPoints = sharedPreference.getString(Const.PICK_POINTS, "");
        dropPoint = sharedPreference.getString(Const.DROP_POINT, "");
        lastLocationLatlng = sharedPreference.getString("lastLocationLatlng", "");
    }

    public void requestDialog() {
        if (!isRequestDialogShowing) {
            isRequestDialogShowing = true;
            LayoutInflater inflater = getLayoutInflater();
            View alertLayout = inflater.inflate(R.layout.requester_details_dialog, null);
            RelativeLayout rl_cancel = (RelativeLayout) alertLayout.findViewById(R.id.rl_cancel);
            TextView tv_name = (TextView) alertLayout.findViewById(R.id.tv_name);
            TextView tv_age = (TextView) alertLayout.findViewById(R.id.tv_age);
            TextView tv_reviews = (TextView) alertLayout.findViewById(R.id.tv_reviews);
            TextView tv_designation = (TextView) alertLayout.findViewById(R.id.tv_designation);
            TextView tv_connections = (TextView) alertLayout.findViewById(R.id.tv_connections);
            TextView tv_fb_friends = (TextView) alertLayout.findViewById(R.id.tv_fb_friends);
            tv_pickup_location = (TextView) alertLayout.findViewById(R.id.tv_pickup_location);
            tv_drop_location = (TextView) alertLayout.findViewById(R.id.tv_drop_location);
            ImageView iv_msg = (ImageView) alertLayout.findViewById(R.id.iv_msg);
            RatingBar ratingBar = (RatingBar) alertLayout.findViewById(R.id.ratingBar);
            ratingBar.setRating(Float.parseFloat(rating.isEmpty() ? "0" : rating));
//        star1 = (ImageView) alertLayout.findViewById(R.id.iv_star1);
//        star2 = (ImageView) alertLayout.findViewById(R.id.iv_star2);
//        star3 = (ImageView) alertLayout.findViewById(R.id.iv_star3);
//        setStar(rating);
            Button btn_view = (Button) alertLayout.findViewById(R.id.btn_view);
            Button btn_reject = (Button) alertLayout.findViewById(R.id.btn_reject);
            Button btn_accept = (Button) alertLayout.findViewById(R.id.btn_accept);
            Button btn_call = (Button) alertLayout.findViewById(R.id.btn_call);

            tv_name.setText(name);
            tv_age.setText(age + " Y");
            tv_reviews.setText(reviews + " Reviews");
            tv_designation.setText(designation);
            tv_pickup_location.setText("Pickup point - " + pickAddress);
            tv_drop_location.setText("Drop Point - " + dropAddress);
            tv_connections.setText("Connections - " + connections);
            tv_fb_friends.setText("Facebook Friends - " + fbFriends);

//        DbAdapter dbAdapter = DbAdapter.getInstance(activity);
//        Cursor cursor = dbAdapter.fetchQuery(DbAdapter.TABLE_NAME_PROFILE);
//        for (int i = 0; i < cursor.getCount(); i++) {
//            offererId = cursor.getString(cursor.getColumnIndex(Const.USERID));
//            cursor.moveToNext();
//        }
//        if (offererId.equalsIgnoreCase("")) {
//            sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
//            offererId = sharedPreference.getString(Const.USERID, "");
////            numberOfSeats = sharedPreference.getString(Const.NUMBER_OF_SEATS, "");
//        }
            offererId = Const.getUserId(activity);

            btn_view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    gotoLiftRequestFragment();
                    alertDialog.dismiss();
                    isRequestDialogShowing = false;
                }
            });

            btn_reject.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    action = "2";
                    if (validate()) {
                        networkHit();
                    }
                }
            });
            btn_accept.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    action = "";
                    if (validate()) {
                        newNetworkHit(true);
                    }
                }
            });
            btn_call.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile)));
                }
            });
            iv_msg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(activity, ChatActivity.class);
                    intent.putExtra(FireConst.CHAT_WITH_USER, requesterId);
                    startActivity(intent);
                }
            });
            rl_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    isRequestDialogShowing = false;
                    sharedPreference.putInt(Const.GOTO, 0);
                }
            });
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
            builder.setView(alertLayout);
            builder.setCancelable(false);
            alertDialog = builder.create();
            alertDialog.show();
        }
    }

    public void confirmedDialog() {
        if (!isConfirmedDialogShowing) {
            isConfirmedDialogShowing = true;
            isShareLocation = true;
            sharedPreference.putBoolean("shareLocation", true);

            LayoutInflater inflater = getLayoutInflater();
            View alertLayout = inflater.inflate(R.layout.offerer_details_dialog, null);
            RelativeLayout rl_cancel = (RelativeLayout) alertLayout.findViewById(R.id.rl_cancel);
            TextView tv_name = (TextView) alertLayout.findViewById(R.id.tv_name);
            TextView tv_age = (TextView) alertLayout.findViewById(R.id.tv_age);
            TextView tv_reviews = (TextView) alertLayout.findViewById(R.id.tv_reviews);
            TextView tv_car_name = (TextView) alertLayout.findViewById(R.id.tv_car_name);
            TextView tv_car_number = (TextView) alertLayout.findViewById(R.id.tv_car_number);
            tv_eta = (TextView) alertLayout.findViewById(R.id.tv_eta);
            RatingBar ratingBar = (RatingBar) alertLayout.findViewById(R.id.ratingBar);
            ratingBar.setRating(Float.parseFloat(rating.isEmpty() ? "0" : rating));
//        star1 = (ImageView) alertLayout.findViewById(R.id.iv_star1);
//        star2 = (ImageView) alertLayout.findViewById(R.id.iv_star2);
//        star3 = (ImageView) alertLayout.findViewById(R.id.iv_star3);
//        setStar(rating);
            Button btn_cancel = (Button) alertLayout.findViewById(R.id.btn_cancel);
            Button btn_msg = (Button) alertLayout.findViewById(R.id.btn_msg);
            Button btn_call = (Button) alertLayout.findViewById(R.id.btn_call);
            final Button btn_start_now = (Button) alertLayout.findViewById(R.id.btn_start_now);

            tv_name.setText(name);
            tv_age.setText(age + " Y");
            tv_reviews.setText(reviews + " Reviews");
            tv_car_name.setText(carName + " - " + type);
            tv_car_number.setText(vehicleNo);
            updateETA();

//        DbAdapter dbAdapter = DbAdapter.getInstance(activity);
//        Cursor cursor = dbAdapter.fetchQuery(DbAdapter.TABLE_NAME_PROFILE);
//        for (int i = 0; i < cursor.getCount(); i++) {
//            requesterId = cursor.getString(cursor.getColumnIndex(Const.USERID));
//            cursor.moveToNext();
//        }
//        if (requesterId.equalsIgnoreCase("")) {
//            sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
//            requesterId = sharedPreference.getString(Const.USERID, "");
////            numberOfSeats = sharedPreference.getString(Const.NUMBER_OF_SEATS, "");
//        }
            requesterId = Const.getUserId(activity);

            btn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    action = "4";
                    if (validate()) {
                        networkHit();
                    }
                }
            });
            btn_msg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent inte = new Intent(activity, ChatActivity.class);
                    inte.putExtra(FireConst.CHAT_WITH_USER, offererId);
                    startActivity(inte);
//                startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", mobile, null)));
                }
            });
            btn_call.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + mobile)));
                }
            });
            btn_start_now.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS);
                    sharedPreference.putString(Const.LATITUDE, String.valueOf(latLng.latitude));
                    sharedPreference.putString(Const.LONGITUDE, String.valueOf(latLng.longitude));
                    createRideStartBean();
                    action = "5";
                    if (validate()) {
                        networkHit();
                    }

//                if (!isStarted) {
//                    isStarted = true;
//                    btn_confirmed.setText("Started");
//                    btn_start_now.setText("Stop");
//                    alertDialog.setCancelable(false);
//                    action = "5";
//                    if (validate()) {
//                        networkHit();
//                    }
//                } else {
//                    isStarted = true;
//                    action = "6";
//                    if (validate()) {
//                        networkHit();
//                    }
//                }

                }
            });
            rl_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                    isConfirmedDialogShowing = false;
                    sharedPreference.putInt(Const.GOTO, 0);
                }
            });
            AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
            builder.setView(alertLayout);
            builder.setCancelable(false);
            alertDialog = builder.create();
            alertDialog.show();
        }
    }

    private void createRideStartBean() {
        rideStartBean = RideStartBean.newInstance();
        rideStartBean.liftId = liftId;
        rideStartBean.offererId = offererId;
        rideStartBean.requesterId = requesterId;
        rideStartBean.name = name;
        rideStartBean.age = age;
        if (rating.isEmpty()) {
            rating = "0";
        }
        rideStartBean.rating = rating;
        rideStartBean.reviews = reviews;
        rideStartBean.pickPoints = pickPoints;
        rideStartBean.dropPoint = dropPoint;
        rideStartBean.profileImage = imageUrl;
        rideStartBean.carNumber = vehicleNo;
        rideStartBean.carName = carName;
        rideStartBean.rate = rate;
        rideStartBean.liftStatus = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS).getInt(Const.LIFT_STATUS, 0);
        rideStartBean.startTime = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS).getLong(Const.START_TIME, 0);
        rideStartBean.seats = Integer.parseInt(SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.NUMBER_OF_SEATS, ""));
//        rideStartBean.lastLocationLatlng = lastLocationLatlng;

//        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS);
//        double lat = Double.parseDouble(sharedPreference.getString(Const.LATITUDE, ""));
//        double lng = Double.parseDouble(sharedPreference.getString(Const.LONGITUDE, ""));

//        rideStartBean.tripStartLatLong = new LatLng(lat, lng);
    }

//    public void msgDialog(String title, String msg) {
//
//        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
//        alertDialogBuilder.setTitle(title);
//        alertDialogBuilder
//                .setMessage(msg)
//                .setCancelable(false)
//                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int id) {
//                        sharedPreference.putInt(Const.GOTO, 0);
//                    }
//                });
//        alertDialog = alertDialogBuilder.create();
//        alertDialog.show();
//    }

    public void msgDialog(String msg) {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
//        alertDialogBuilder.setTitle(title);
        alertDialogBuilder
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        sharedPreference.putInt(Const.GOTO, 0);
                    }
                });
        alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    private void updateETA() {
        if (tv_eta != null) {
            if (eta.equalsIgnoreCase("") || eta.equalsIgnoreCase("null")) {
                tv_eta.setText("ETA - Not Available");
            } else {
                tv_eta.setText("ETA - " + eta);
            }
        }
    }

    public boolean validate() {
        jsonObject = new JsonObject();
        jsonObject.addProperty(Const.LIFT_ID, liftId);
        jsonObject.addProperty(Const.OFFERER_ID, offererId);
        jsonObject.addProperty(Const.REQUESTER_ID, requesterId);
        jsonObject.addProperty(Const.ACTION, action);
        jsonObject.addProperty(Const.NUMBER_OF_SEATS, "");
        jsonObject.addProperty("pickupLatLong", HomeActivity.latLng.latitude + "," + HomeActivity.latLng.longitude);

        return true;
    }

    public void networkHit() {
        if (Helper.isConnected(activity)) {
            if (!action.equalsIgnoreCase("1")) {
                progress = new Progress(activity);
                progress.show();
            }
            Log.e("json", jsonObject.toString());
            Ion.with(activity)
                    .load(API.API_SEND_REQUEST)
                    .setTimeout(45 * 1000)
                    .setJsonObjectBody(jsonObject)
                    .asString()
                    .setCallback(new FutureCallback<String>() {

                                     @Override
                                     public void onCompleted(Exception e, String jsonString) {
                                         if (!action.equalsIgnoreCase("1")) {
                                             progress.hide();
                                         }
                                         if (e == null) {
                                             if (jsonString != null && !jsonString.isEmpty()) {
                                                 try {
                                                     Log.e("json", jsonString);

                                                     JSONObject jsonObject = new JSONObject(jsonString);
                                                     if (jsonObject.optBoolean(Const.IS_SUCCESS)) {
//                                        Helper.showSnackBar(linearParent, jsonObject.optString(Const.MESSAGE));
                                                         if (alertDialog != null) {
                                                             alertDialog.dismiss();
                                                             isRequestDialogShowing = false;
                                                             isConfirmedDialogShowing = false;
                                                         }
                                                         if (action.equalsIgnoreCase("1") || action.equalsIgnoreCase("2")) {
                                                             if (action.equalsIgnoreCase("1")) {
//                                                autoLocationCancelHandler.removeCallbacks(autoCancelLocationRunnable);
                                                                 JSONObject pushMessage = jsonObject.optJSONObject("pushMessage");
                                                                 liftId = pushMessage.optString(Const.LIFT_ID);
                                                                 name = pushMessage.optString(Const.NAME);
                                                                 age = pushMessage.optString(Const.AGE);
                                                                 imageUrl = pushMessage.optString(Const.PROFILE_IMAGE);
                                                                 if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("https")) {
                                                                     imageUrl = imageUrl.substring(imageUrl.lastIndexOf("https:"));
                                                                 } else if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("http")) {
                                                                     imageUrl = imageUrl.substring(imageUrl.lastIndexOf("http:"));
                                                                 }
                                                                 eta = pushMessage.optString(Const.ETA);
                                                                 vehicleNo = pushMessage.optString(Const.VEHICLE_NUMBER);
                                                                 reviews = pushMessage.optString(Const.REVIEWS);
                                                                 rating = pushMessage.optString(Const.RATING);
                                                                 mobile = pushMessage.optString(Const.MOBILE);
                                                                 carName = pushMessage.optString(Const.CAR_NAME);
                                                                 carDetails = jsonObject.optString(Const.CAR_DETAILS);
                                                                 userId = pushMessage.optString(Const.USERID);
                                                                 offererId = pushMessage.optString(Const.USERID);
                                                                 type = pushMessage.optString(Const.TYPE);
                                                                 pickPoints = pushMessage.optString(Const.PICK_POINTS);
                                                                 dropPoint = pushMessage.optString(Const.DROP_POINT);
                                                                 saveOffererDetails();

                                                                 sharedPreference.putInt(Const.GOTO, Const.TYPE2);
                                                                 confirmedDialog();
                                                             } else {
                                                                 sharedPreference.putInt(Const.GOTO, 0);
                                                             }
                                                         }
                                                         if (action.equalsIgnoreCase("4")) {
                                                             isShareLocation = false;
                                                             sharedPreference.putBoolean("shareLocation", false);
                                                             sharedPreference.putInt(Const.GOTO, 0);
//                                            if (action.equalsIgnoreCase("6")) {
//                                                tripStopLatLong = latLng;
//                                            }
                                                         }
                                                         if (action.equalsIgnoreCase("5")) {
//                                            isShareLocation = false;
//                                            SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).putBoolean("shareLocation", false);
                                                             rate = jsonObject.optJSONObject(Const.RESULT).optString(Const.RATE);
                                                             sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_OFFERER_DETAILS);
                                                             sharedPreference.putString(Const.RATE, rate);
                                                             sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
                                                             sharedPreference.putString(Const.LIFT_ID, liftId);
                                                             sharedPreference.putInt(Const.GOTO, Const.END_LIFT);
                                                             sharedPreference.putLong("rideStartTime", System.currentTimeMillis());
                                                             rideStartBean.rate = rate;
                                                             gotoEndLiftFragment();
                                                         }
                                                         if (HomeActivity.isLiftRequestFragmentVisible) {
                                                             ((HomeActivity) activity).go2Home();
                                                         }
                                                     } else {
                                                         Helper.showSnackBar(linearParent, jsonObject.optString(Const.MESSAGE));
                                                     }
                                                 } catch (Exception ex) {
                                                     ex.printStackTrace();
                                                     if (!action.equalsIgnoreCase("1")) {
                                                         Helper.showSnackBar(linearParent, Const.INTERNAL_ERROR);
                                                     } else {
                                                         networkHit();
                                                     }
                                                 }
                                             } else {
                                                 if (!action.equalsIgnoreCase("1")) {
                                                     Helper.showSnackBar(linearParent, Const.NETWORK_ERROR);
                                                 } else {
                                                     networkHit();
                                                 }
                                             }
                                         } else {
                                             e.printStackTrace();
                                             Helper.showSnackBar(linearParent, e.getMessage());
                                         }
                                     }
                                 }
                    );
        } else {
            Helper.showSnackBar(linearParent, Const.NO_INTERNET);
        }
    }

    public void newNetworkHit(final boolean isFromDialog) {
        if (Helper.isConnected(activity)) {
            progress = new Progress(activity);
            progress.show();
            Log.e("json", jsonObject.toString());
            Ion.with(activity)
                    .load(API.API_ACTION_ACCEPT)
                    .setTimeout(45 * 1000)
                    .setJsonObjectBody(jsonObject)
                    .asString()
                    .setCallback(new FutureCallback<String>() {

                        @Override
                        public void onCompleted(Exception e, String jsonString) {
                            progress.hide();
                            if (e == null) {
                                if (jsonString != null && !jsonString.isEmpty()) {
                                    try {
                                        Log.e("json", jsonString);

                                        JSONObject jsonObject = new JSONObject(jsonString);
                                        if (jsonObject.optBoolean(Const.IS_SUCCESS)) {
                                            autoLocationCancelHandler.removeCallbacks(autoCancelLocationRunnable);

                                            if (networkHitRunnable != null) {
                                                networkHitHandler.removeCallbacks(networkHitRunnable);
                                            }
                                            networkHitHandler.postDelayed(networkHitRunnable, 10 * 1000);
                                            //Helper.showSnackBar(linearParent, jsonObject.optString(Const.MESSAGE));
                                            if (isFromDialog) {
                                                if (alertDialog != null) {
                                                    alertDialog.dismiss();
                                                    isRequestDialogShowing = false;
                                                    isConfirmedDialogShowing = false;
                                                }
                                            } else {
                                                go2Home();
                                            }
                                        } else {
                                            Helper.showSnackBar(linearParent, jsonObject.optString(Const.MESSAGE));
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        Helper.showSnackBar(linearParent, Const.INTERNAL_ERROR);
                                    }
                                } else {
                                    Helper.showSnackBar(linearParent, Const.NETWORK_ERROR);
                                }
                            } else {
                                e.printStackTrace();
                                Helper.showSnackBar(linearParent, e.getMessage());
                            }
                        }
                    });
        } else {
            Helper.showSnackBar(linearParent, Const.NO_INTERNET);
        }
    }

    public void networkHitRequesterList() {
        if (Helper.isConnected(activity)) {
            if (latLng != null) {
                jsonObject = new JsonObject();
                jsonObject.addProperty(Const.LIFT_ID, SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString("LIFT_ID", ""));
                jsonObject.addProperty(Const.OFFERER_ID, Const.getUserId(activity));
                jsonObject.addProperty("dropLatLong", latLng.latitude + "," + latLng.longitude);
                if (distanceHashMap.size() > 0) {
                    JsonArray jsonArray = new JsonArray();
                    for (Object o : distanceHashMap.entrySet()) {
                        Map.Entry pair = (Map.Entry) o;
                        String key = String.valueOf(pair.getKey());
                        String value = distanceHashMap.get(key);
                        String status = statusHashMap.get(key);
                        String pickPoint = pickPointHashMap.get(key);

                        JsonObject object = new JsonObject();
                        object.addProperty(Const.REQUESTER_ID, key);
                        object.addProperty(Const.DISTANCE, value);
                        object.addProperty("status", status);
                        object.addProperty(Const.PICKUP_POINT, pickPoint);
                        jsonArray.add(object);
                    }
                    jsonObject.add("updateData", jsonArray);
                }

                Log.e("json", jsonObject.toString());
                Ion.with(activity)
                        .load(API.API_ACCEPTED_REQUESTER_LIST)
                        .setTimeout(45 * 1000)
                        .setJsonObjectBody(jsonObject)
                        .asString()
                        .setCallback(new FutureCallback<String>() {

                            @Override
                            public void onCompleted(Exception e, String jsonString) {
                                if (jsonString != null && !jsonString.isEmpty()) try {
                                    Log.e("json", jsonString);
//                                    jsonString = "{\"isSuccess\":true,\"message\":\"Requester List displayed successfully \",\"Result\":[{\"userId\":\"34\",\"name\":\"lGullak Sharma\",\"age\":\"12\",\"profileImage\":\"https:\\/\\/fbcdn-profile-a.akamaihd.net\\/hprofile-ak-xpt1\\/v\\/t1.0-1\\/12106961_179505742383093_1717545916104035561_n.jpg?oh=59b4f4c8f1f6a9fb24e38caa968f9458&oe=57C9CE59&__gda__=1473277857_3f2995fc3898aa72594c499ab611d76b\",\"pickupPoint\":\"28.62877,77.37901\",\"dropPoint\":\"28.45946,77.02664\",\"numberOfSeats\":\"1\",\"startTime\":\"00:00:00\",\"rate\":\"8\",\"reviews\":1,\"rating\":null},{\"userId\":\"34\",\"name\":\"lGullak Sharma\",\"age\":\"12\",\"profileImage\":\"https:\\/\\/fbcdn-profile-a.akamaihd.net\\/hprofile-ak-xpt1\\/v\\/t1.0-1\\/12106961_179505742383093_1717545916104035561_n.jpg?oh=59b4f4c8f1f6a9fb24e38caa968f9458&oe=57C9CE59&__gda__=1473277857_3f2995fc3898aa72594c499ab611d76b\",\"pickupPoint\":\"28.62877,77.37901\",\"dropPoint\":\"28.45946,77.02664\",\"numberOfSeats\":\"1\",\"startTime\":\"00:00:00\",\"rate\":\"8\",\"reviews\":1,\"rating\":null}]}";
                                    if (isStatusEnd) {
                                        isStatusEnd = false;
                                        progress.hide();
                                        Helper.showSnackBar(linearParent, "Lift ended successfully.");
                                    }
                                    JSONObject object = new JSONObject(jsonString);
                                    if (object.optBoolean(Const.IS_SUCCESS)) {
                                        trackerBeanArrayList.clear();
                                        JSONArray resultArray = object.optJSONArray(Const.RESULT);
                                        listSize = resultArray.length();
                                        if (listSize == 0) {
                                            isRequesterAdded = false;
                                        }
                                        for (int i = 0; i < listSize; i++) {
                                            JSONObject jsonObject = resultArray.optJSONObject(i);
                                            TrackerBean trackerBean = new TrackerBean();
                                            trackerBean.liftId = jsonObject.optString(Const.LIFT_ID);
                                            trackerBean.name = jsonObject.optString(Const.NAME);
                                            String imageUrl = jsonObject.optString(Const.PROFILE_IMAGE);
                                            if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("https")) {
                                                imageUrl = imageUrl.substring(imageUrl.lastIndexOf("https:"));
                                            } else if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("http")) {
                                                imageUrl = imageUrl.substring(imageUrl.lastIndexOf("http:"));
                                            }
                                            trackerBean.imageUrl = imageUrl;
                                            trackerBean.age = jsonObject.optString(Const.AGE);
                                            trackerBean.reviews = jsonObject.optString(Const.REVIEWS);
                                            trackerBean.rating = jsonObject.optString(Const.RATING);
                                            trackerBean.requesterId = jsonObject.optString(Const.USERID);
                                            trackerBean.pickPoints = jsonObject.optString(Const.PICKUP_POINT);
                                            trackerBean.dropPoint = jsonObject.optString(Const.DROP_POINT);
                                            trackerBean.seats = jsonObject.optString(Const.NUMBER_OF_SEATS);
                                            trackerBean.rate = jsonObject.optString(Const.RATE);
                                            trackerBean.time = jsonObject.optString(Const.START_TIME);
                                            trackerBean.distanceInMeterFloat = Float.parseFloat(jsonObject.optString(Const.DISTANCE));

                                            if (!distanceHashMap.containsKey(trackerBean.requesterId)) {
                                                distanceHashMap.put(trackerBean.requesterId, "0.0");
                                            }
                                            if (!statusHashMap.containsKey(trackerBean.requesterId)) {
                                                statusHashMap.put(trackerBean.requesterId, "");
                                            }
                                            if (!pickPointHashMap.containsKey(trackerBean.requesterId)) {
                                                pickPointHashMap.put(trackerBean.requesterId, trackerBean.pickPoints);
                                            }
                                            if (!trackerBean.time.equalsIgnoreCase("00:00:00")) {
                                                isRequesterAdded = true;
                                                LatLng pickPoint = new LatLng(Double.parseDouble(trackerBean.pickPoints.split(",")[0]), Double.parseDouble(trackerBean.pickPoints.split(",")[1]));

                                                float distance[] = new float[2];
                                                Location.distanceBetween(pickPoint.latitude, pickPoint.longitude, latLng.latitude, latLng.longitude, distance);
                                                float d = distance[0];

                                                if (d > 200) {
//                                                    float f = Float.parseFloat(distanceHashMap.get(requesterId)) + d;
                                                    float f = trackerBean.distanceInMeterFloat + d;
                                                    distanceHashMap.put(requesterId, String.valueOf(f));
                                                    pickPointHashMap.put(requesterId, latLng.latitude + "," + latLng.longitude);
                                                }

//                                                new Distance(pickPoint, HomeActivity.latLng, trackerBean.requesterId);
//                                            DownloadTask downloadTask = new DownloadTask();
//                                            downloadTask.execute(getDirectionsUrl(pickPoint, HomeActivity.latLng), "" + trackerBean.requesterId);

                                            }
                                            trackerBeanArrayList.add(trackerBean);
                                        }
                                        DbAdapter.getInstance(activity).setRequester(trackerBeanArrayList);
                                        if (trackerFragment != null) {
                                            trackerFragment.notifyAdapter();
                                        }
                                    } else {
                                        trackerBeanArrayList.clear();
                                        if (trackerFragment != null) {
                                            trackerFragment.notifyAdapter();
                                        }
//                                        Helper.showSnackBar(linearParent, object.optString(Const.MESSAGE));
                                    }
                                } catch (Exception ex) {
                                    ex.printStackTrace();
//                                    Helper.showSnackBar(linearParent, Const.NETWORK_ERROR);
                                }
                                else {
//                                Helper.showSnackBar(linearParent, Const.TIMEOUT);
                                }
                            }
                        });
            }
        } else {
//            Helper.showSnackBar(linearParent, Const.NO_INTERNET);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);
        isReceiverRegistered = true;
        if (networkHitRunnable != null) {
            networkHitHandler.removeCallbacks(networkHitRunnable);
        }
        networkHitHandler.postDelayed(networkHitRunnable, 10 * 1000);
    }

    public Runnable networkHitRunnable = new Runnable() {
        @Override
        public void run() {
            Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.frag_container);
            if (networkHitRunnable != null) {
                networkHitHandler.removeCallbacks(networkHitRunnable);
            }
            if (fragment instanceof TrackerFragment || fragment instanceof TrackerUserFragment) {
//                if(!isRequesterAdded) {
                networkHitRequesterList();
//                }
            }
            if (fragment instanceof EndLiftFragment) {
                ((EndLiftFragment) fragment).onResume();
            }
            networkHitHandler.postDelayed(networkHitRunnable, 10 * 1000);
        }
    };

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
        isReceiverRegistered = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        progress.dismiss();
    }

    public void getSource(LatLng latLng) {
        try {
            Log.e("address latlng", latLng.latitude + ", " + latLng.longitude);
            if (Helper.isConnected(activity)) {
                Ion.with(activity)
                        .load("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latLng.latitude + "," + latLng.longitude + "&sensor=true")
                        .setTimeout(45 * 1000)
                        .asString()
                        .setCallback(new FutureCallback<String>() {
                            @Override
                            public void onCompleted(Exception e, String jsonString) {
                                if (jsonString != null && !jsonString.isEmpty()) {
                                    Log.e("json", jsonString);
                                    try {
                                        JSONObject jsonObject = new JSONObject(jsonString);
                                        JSONArray addressArray = jsonObject.optJSONArray("results");
                                        JSONObject addressObject = addressArray.optJSONObject(0);
                                        JSONArray array = addressObject.optJSONArray("address_components");
                                        String address = "";
                                        JSONObject object;
                                        for (int i = 0; i < 3; i++) {
                                            object = array.optJSONObject(i);
                                            if (i == 0) {
                                                address = object.optString("short_name");
                                            } else {
                                                if (address.equalsIgnoreCase("unnamed road")) {
                                                    address = object.optString("short_name");
                                                } else {
                                                    address = address + ", " + object.optString("short_name");
                                                }
                                            }
                                        }
                                        tv_pickup_location.setText("Pickup point - " + address);
                                        pickAddress = address;
                                        setAddressInLiftRequestFragment();
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                }

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

    public void getDestination(LatLng latLng) {
        try {
            Log.e("address latlng", latLng.latitude + ", " + latLng.longitude);
            if (Helper.isConnected(activity)) {
                Ion.with(activity)
                        .load("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latLng.latitude + "," + latLng.longitude + "&sensor=true")
                        .setTimeout(45 * 1000)
                        .asString()
                        .setCallback(new FutureCallback<String>() {
                            @Override
                            public void onCompleted(Exception e, String jsonString) {
                                if (jsonString != null && !jsonString.isEmpty()) {
                                    Log.e("json", jsonString);
                                    try {
                                        JSONObject jsonObject = new JSONObject(jsonString);
                                        JSONArray addressArray = jsonObject.optJSONArray("results");
                                        JSONObject addressObject = addressArray.optJSONObject(0);
                                        JSONArray array = addressObject.optJSONArray("address_components");
                                        String address = "";
                                        JSONObject object;
                                        for (int i = 0; i < 3; i++) {
                                            object = array.optJSONObject(i);
                                            if (i == 0) {
                                                address = object.optString("short_name");
                                            } else {
                                                if (address.equalsIgnoreCase("unnamed road")) {
                                                    address = object.optString("short_name");
                                                } else {
                                                    address = address + ", " + object.optString("short_name");
                                                }
                                            }
                                        }
                                        tv_drop_location.setText("Drop Point - " + address);
                                        dropAddress = address;
                                        setAddressInLiftRequestFragment();
                                    } catch (Exception e1) {
                                        e1.printStackTrace();
                                    }
                                }

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


    public interface GetLocationUpdate {
        void update(Location location);
    }

    public interface UpdateTracker {
        void updateLocationOnMap(JSONObject jsonObject);
    }

    public void setTrackerFragment(TrackerFragment fragment) {
        trackerFragment = fragment;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    public void helpDialog() {
        TimerTask task = new RunMeTask();
        timer = new Timer();
        timer.scheduleAtFixedRate(task, 200, 1000);
        sec = 0;

        LayoutInflater inflater = activity.getLayoutInflater();
        View alertLayout = inflater.inflate(R.layout.dialog_help, null);
        circleProgressView = (CircleProgressView) alertLayout.findViewById(R.id.circleView);
        TextView tv_msg = (TextView) alertLayout.findViewById(R.id.tv_msg);
        String mobile = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.PHONE_EM, "");
        tv_msg.setText("An Emergency SMS will be sent to your Emergency Contact Number (" + mobile + ").");

        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
//        builder.setTitle("Emergency Alert");
        builder.setView(alertLayout);
        builder.setCancelable(false);
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                timer.cancel();
                sec = 0;
            }
        });
        helpDialog = builder.create();
        helpDialog.show();
    }

    public void helpDialog2() {
        LayoutInflater inflater = activity.getLayoutInflater();
        View alertLayout = inflater.inflate(R.layout.dialog_help_2, null);
        circleProgressView = (CircleProgressView) alertLayout.findViewById(R.id.circleView);
        TextView tv_msg = (TextView) alertLayout.findViewById(R.id.tv_msg);
        TextView tv_contact = (TextView) alertLayout.findViewById(R.id.tv_contact);
        TextView tv_police = (TextView) alertLayout.findViewById(R.id.tv_police);
        contact_no = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL).getString(Const.PHONE_EM, "");
        tv_msg.setText("An Emergency SMS was sent to your Emergency Contact Number (" + contact_no + ").");
        tv_contact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!contact_no.equalsIgnoreCase("")) {
                    startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + contact_no)));
                }
            }
        });

        tv_police.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + police)));
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.AppTheme));
//        builder.setTitle("Emergency Alert");
        builder.setView(alertLayout);
        builder.setCancelable(true);
        helpDialog = builder.create();
        helpDialog.show();
    }

    public class RunMeTask extends TimerTask {
        @Override
        public void run() {
            if (helpDialog != null && helpDialog.isShowing()) {
                if (sec == 10) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            helpDialog.dismiss();
                            timer.cancel();
                            networkHitHelp();
                            sec++;
                        }

                    });
                } else {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            circleProgressView.setValue(sec);
                            sec++;
                        }
                    });

                }
            }
        }
    }

    public void networkHitHelp() {
        if (Helper.isConnected(activity)) {
        progress.show();
            JsonObject object = new JsonObject();
            object.addProperty(Const.USERID, Const.getUserId(activity));
            Log.e("json", object.toString());
            Ion.with(activity)
                    .load(API.API_HELP)
                    .setTimeout(45 * 1000)
                    .setJsonObjectBody(object)
                    .asString()
                    .setCallback(new FutureCallback<String>() {

                        @Override
                        public void onCompleted(Exception e, String jsonString) {
                            if (e == null) {
                                if (jsonString != null && !jsonString.isEmpty()) {
                                    progress.hide();
                                    try {
                                        Log.e("json", jsonString);

                                        JSONObject jsonObject = new JSONObject(jsonString);
                                        if (jsonObject.optBoolean(Const.IS_SUCCESS)) {
                                            helpDialog2();
                                            Helper.showSnackBar(linearParent, "Emergency Help request sent succesfully to Emergency Contact.");
                                        } else {
//                                            networkHitHelp();
                                            Helper.showSnackBar(linearParent, "Emergency Help request failed. Try again...");
                                        }
                                    } catch (Exception ex) {
                                        ex.printStackTrace();
                                        Helper.showSnackBar(linearParent, Const.INTERNAL_ERROR);
//                                        progress.hide();
                                    }
                                } else {
                                    Helper.showSnackBar(linearParent, Const.NETWORK_ERROR);
//                                    networkHitHelp();
                                }
                            } else {
                                e.printStackTrace();
                                Helper.showSnackBar(linearParent, e.getMessage());
                            }
                        }
                    });
        } else {
//            progress.hide();
            Helper.showSnackBar(linearParent, Const.NO_INTERNET);
        }
    }
    /*public void autoCancelLocationUpdateIfNoLiftRequest() {
        sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
        autoCancelRequestTime = sharedPreference.getLong("autoCancelLocationUpdateTime", 0l);
        Log.e("autoCancelLocationUp", autoCancelRequestTime + "");
        if ((autoCancelRequestTime + 30 * 60 * 1000) < System.currentTimeMillis()) {
            autoCancelRequestTime = 0l;
        } else {
            autoCancelRequestTime = (autoCancelRequestTime + 30 * 60 * 1000) - System.currentTimeMillis();
        }
        autoLocationCancelHandler.postDelayed(autoCancelLocationRunnable, autoCancelRequestTime);
    }*/

//    private void setStar(final String rating) {
//        try {
//            switch (rating) {
//                case "1":
//                    star1.getDrawable().setColorFilter(getResources().getColor(R.color.darkGreen), PorterDuff.Mode.SRC_ATOP);
//                    break;
//                case "2":
//                    star1.getDrawable().setColorFilter(getResources().getColor(R.color.darkGreen), PorterDuff.Mode.SRC_ATOP);
//                    star2.getDrawable().setColorFilter(getResources().getColor(R.color.darkGreen), PorterDuff.Mode.SRC_ATOP);
//                    break;
//                case "3":
//                    star1.getDrawable().setColorFilter(getResources().getColor(R.color.darkGreen), PorterDuff.Mode.SRC_ATOP);
//                    star2.getDrawable().setColorFilter(getResources().getColor(R.color.darkGreen), PorterDuff.Mode.SRC_ATOP);
//                    star3.getDrawable().setColorFilter(getResources().getColor(R.color.darkGreen), PorterDuff.Mode.SRC_ATOP);
//                    break;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

   /* private class Distance {

        public Distance(LatLng source, final LatLng destination, final String requesterId) {

            String key = "key=AIzaSyCpdz5wefjc6iaVhR5RhBqojrCa_V4faMY";
            String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + source.latitude + "," + source.longitude + "&destinations=" + destination.latitude + "," + destination.longitude + "&mode=driving&" + key;
            Ion.with(activity)
                    .load(url)
                    .setTimeout(45 * 1000)
                    .asString()
                    .setCallback(new FutureCallback<String>() {

                        @Override
                        public void onCompleted(Exception e, String jsonString) {
                            if (jsonString != null && !jsonString.isEmpty()) {
                                try {
                                    Log.e("json", jsonString);

                                    JSONObject object = new JSONObject(jsonString);
                                    JSONArray rows = object.optJSONArray("rows");
                                    JSONObject zero = rows.optJSONObject(0);
                                    JSONArray elements = zero.optJSONArray("elements");
                                    JSONObject zero2 = elements.optJSONObject(0);
                                    JSONObject distance = zero2.optJSONObject(Const.DISTANCE);
                                    int d = distance.optInt("value");

//                                if (Float.parseFloat(distanceHashMap.get(requesterId)) < d) {
//                                    distanceHashMap.put(requesterId, String.valueOf(d));
//                                }
                                    if (d > 50) {
                                        float f = Float.parseFloat(distanceHashMap.get(requesterId)) + d;
                                        distanceHashMap.put(requesterId, String.valueOf(f));
                                        pickPointHashMap.put(requesterId, destination.latitude + "," + destination.longitude);
                                    }
                                } catch (Exception ex) {
                                    ex.printStackTrace();
//                                    Helper.showSnackBar(linearParent, Const.NETWORK_ERROR);
                                }
                            }
                            count++;
                            if (count == listSize) {
                                count = 0;
                                networkHitRequesterList();
                            }
                        }
                    });
        }
    }*/


    private class DownloadTask extends AsyncTask<String, Void, String> {
        String requesterId = "0";

        // Downloading data in non-ui thread
        @Override
        protected String doInBackground(String... url) {
            // For storing data from web service
            String data = "";
            try {
                // Fetching the data from web service
                data = downloadUrl(url[0]);
                requesterId = url[1];
            } catch (Exception e) {
                Log.e("Background Task", e.toString());
            }
            return data;
        }

        // Executes in UI thread, after the execution of
        // doInBackground()
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            ParserTask parserTask = new ParserTask();
            // Invokes the thread for parsing the JSON data
            parserTask.execute(result, requesterId);
        }
    }

    private String getDirectionsUrl(LatLng... latLngs) {
        // Origin of route
        String str_origin = "origin=" + latLngs[0].latitude + "," + latLngs[0].longitude;
        // Destination of route
        String str_dest = "destination=" + latLngs[1].latitude + "," + latLngs[1].longitude;
        // Sensor enabled
        String sensor = "sensor=false";
        // Waypoints
//        String waypoints = "waypoints=via:-" + latLngs[2].latitude + "," + latLngs[2].longitude + "|via:-" + latLngs[3].latitude + "," + latLngs[3].longitude + "|via:-" + latLngs[4].latitude + "," + latLngs[4].longitude;
        String alternative = "alternatives=true";
        String mode = "mode=driving";
        String unit = "units=metric";
        String key = "key=AIzaSyCpdz5wefjc6iaVhR5RhBqojrCa_V4faMY";
        // Building the parameters to the web service
        String parameters = str_origin + "&" + str_dest + "&" + unit + /*"&" + waypoints +*/ "&" + alternative + "&" + sensor + "&" + key;
        // Output format
        String output = "json";
        // Building the url to the web service
        String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
//        url = "http://maps.googleapis.com/maps/api/directions/json?origin=46.839382,-100.771373&destination=46.791115,-100.763650&units=imperial&alternatives=true&sensor=false";
        return url;
    }

    /**
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);
            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();
            // Connecting to url
            urlConnection.connect();
            // Reading data from url
            iStream = urlConnection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            data = sb.toString();
            br.close();
        } catch (Exception e) {
            Log.e("downloading url", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private class ParserTask extends AsyncTask<String, Integer, String> {
        String requesterId = "0";

        // Parsing the data in non-ui thread
        @Override
        protected String doInBackground(String... jsonData) {
            JSONObject jObject;
            String routes = "";
            try {
                jObject = new JSONObject(jsonData[0]);
                requesterId = jsonData[1];
                DirectionsJSONParserDistance parserDistance = new DirectionsJSONParserDistance();
                // Starts parsing data
                routes = parserDistance.parse(jObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return routes;
        }

        // Executes in UI thread, after the parsing process
        @Override
        protected void onPostExecute(String distance) {
            if (distance != null && !distance.equalsIgnoreCase("")) {
                float d = 0.0f;
                if (distance.contains("km")) {
//                    d = Float.valueOf(distance.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[0]) * 1000f;
                    d = Float.valueOf(distance.split("km")[0].trim()) * 1000f;
                } else {
//                    d = Float.valueOf(distance.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)")[0]);
                    d = Float.valueOf(distance.split("m")[0].trim());
                }
                if (Float.parseFloat(distanceHashMap.get(requesterId)) < d) {
                    distanceHashMap.put(requesterId, String.valueOf(d));
                }
//                if (arrayList.get(Integer.parseInt(position)).distanceInMeterFloat < d) {
//                    arrayList.get(Integer.parseInt(position)).distanceInMeterFloat = d;
//                }
//                distanceHashMap.get()
            }
        }
    }

   /* public void onPushReceived(String jsonString) {
        Log.e("push", jsonString);
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(jsonString);
            if (jsonObject.has("pushType")) {
                String pushType = jsonObject.optString("pushType");
                sharedPreference = SharedPreference.getInstance(activity, SharedPreference.PREF_TYPE_GENERAL);
                String pushMessage="";
                switch (pushType) {
                    case "type1"://Lift Request
                        liftId = jsonObject.optString(Const.LIFT_ID);
                        name = jsonObject.optString(Const.NAME);
                        imageUrl = jsonObject.optString(Const.PROFILE_IMAGE);
                        if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("https")) {
                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("https:"));
                        } else if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("http")) {
                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("http:"));
                        }
                        age = jsonObject.optString(Const.AGE);
                        fbFriends = jsonObject.optString(Const.FB_FRIENDS);
                        reviews = jsonObject.optString(Const.REVIEWS);
                        rating = jsonObject.optString(Const.RATING);
                        mobile = jsonObject.optString(Const.MOBILE);
                        designation = jsonObject.optString(Const.DESIGNATION);
                        userId = jsonObject.optString(Const.USERID);
                        requesterId = jsonObject.optString(Const.USERID);
                        connections = jsonObject.optString(Const.CONNECTIONS);
                        pickPoints = jsonObject.optString(Const.PICK_POINTS);
                        pick = new LatLng(Double.parseDouble(pickPoints.split(",")[0]), Double.parseDouble(pickPoints.split(",")[1]));
                        getSource(pick);
                        dropPoint = jsonObject.optString(Const.DROP_POINT);
                        drop = new LatLng(Double.parseDouble(dropPoint.split(",")[0]), Double.parseDouble(dropPoint.split(",")[1]));
                        startPoints = jsonObject.optString("startPoint");
                        start = new LatLng(Double.parseDouble(startPoints.split(",")[0]), Double.parseDouble(startPoints.split(",")[1]));
                        getDestination(drop);
                        saveRequesterDetails();
                        sharedPreference.putInt(Const.GOTO, Const.TYPE1);
                        requestDialog();
                        break;

                    case "type5"://Lift Request cancelled by the requester.
                        sharedPreference.putInt(Const.GOTO, Const.TYPE5);
                        pushMessage = jsonObject.optString("pushMessage");
                        msgDialog(pushMessage);
                        sharedPreference.putString(Const.TYPE5+"", pushMessage);
                        break;

                    case "type2"://Request Accepted

                    case "type3"://Request Rejected

                        liftId = jsonObject.optString(Const.LIFT_ID);
                        name = jsonObject.optString(Const.NAME);
                        imageUrl = jsonObject.optString(Const.PROFILE_IMAGE);
                        if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("https")) {
                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("https:"));
                        } else if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("http")) {
                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("http:"));
                        }
                        age = jsonObject.optString(Const.AGE);
                        eta = jsonObject.optString(Const.ETA);
                        vehicleNo = jsonObject.optString(Const.VEHICLE_NUMBER);
                        reviews = jsonObject.optString(Const.REVIEWS);
                        rating = jsonObject.optString(Const.RATING);
                        mobile = jsonObject.optString(Const.MOBILE);
                        carName = jsonObject.optString(Const.CAR_NAME);
                        carDetails = jsonObject.optString(Const.CAR_DETAILS);
                        userId = jsonObject.optString(Const.USERID);
                        offererId = jsonObject.optString(Const.USERID);
                        type = jsonObject.optString(Const.TYPE);
                        pickPoints = jsonObject.optString(Const.PICK_POINTS);
                        dropPoint = jsonObject.optString(Const.DROP_POINT);
                        saveOffererDetails();
                        if (pushType.equalsIgnoreCase("type2")) {
                            sharedPreference.putInt(Const.GOTO, Const.TYPE2);
                            confirmedDialog();
                        } else if (pushType.equalsIgnoreCase("type3")) {
                            sharedPreference.putInt(Const.GOTO, Const.TYPE3);
                            pushMessage = jsonObject.optString("pushMessage");
                            msgDialog(pushMessage);
                            sharedPreference.putString(Const.TYPE3+"", pushMessage);
//                            Your request for " Start point " to " End Point" is rejected by the " Offerer Name"
                        }
                        break;
                    case "type6"://Lift Started
//                        liftId = jsonObject.optString(Const.LIFT_ID);
                        name = jsonObject.optString(Const.NAME);
//                        imageUrl = jsonObject.optString(Const.PROFILE_IMAGE);
//                        if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("https")) {
//                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("https:"));
//                        } else if (imageUrl.length() >= 6 && imageUrl.substring(6).contains("http")) {
//                            imageUrl = imageUrl.substring(imageUrl.lastIndexOf("http:"));
//                        }
//                        age = jsonObject.optString(Const.AGE);
//                        reviews = jsonObject.optString(Const.REVIEWS);
//                        rating = jsonObject.optString(Const.RATING);
//                        userId = jsonObject.optString(Const.USERID);
//                        requesterId = jsonObject.optString(Const.USERID);
//                        pickPoints = jsonObject.optString(Const.PICK_POINTS);
//                        dropPoint = jsonObject.optString(Const.DROP_POINT);

                        rate = jsonObject.optString(Const.RATE);
                        sharedPreference.putInt(Const.GOTO, Const.TYPE6);
                        pushMessage = jsonObject.optString("pushMessage");
                        msgDialog(pushMessage);
                        sharedPreference.putString(Const.TYPE6+"", pushMessage);
                        break;
                    case "type7"://Lift Stopped
                        sharedPreference.putInt(Const.GOTO, Const.TYPE7);
//                        msgDialog("Ride Stopped", "Ride is stopped by the requester.");
                        break;
                    case "type8"://Ride End
                        PaymentCompleteBean pcBean = PaymentCompleteBean.newInstance();

                        pickPoints = jsonObject.optString(Const.PICKUP_POINT);
                        dropPoint = jsonObject.optString(Const.DROP_POINT);

                        pcBean.liftId = jsonObject.optString(Const.LIFT_ID);
                        pcBean.userId = jsonObject.optString("ReqesterId");
                        pcBean.name = jsonObject.optString("ReqesterName");
                        pcBean.pickPoint = new LatLng(Double.parseDouble(pickPoints.split(",")[0]), Double.parseDouble(pickPoints.split(",")[1]));
                        pcBean.dropPoint = new LatLng(Double.parseDouble(dropPoint.split(",")[0]), Double.parseDouble(dropPoint.split(",")[1]));

//                        float[] distance = new float[2];
//                        Location.distanceBetween(pcBean.pickPoint.latitude, pcBean.pickPoint.longitude, pcBean.dropPoint.latitude, pcBean.dropPoint.longitude, distance);
//                        pcBean.distance = distance[0];
                        pcBean.distance = Float.parseFloat(jsonObject.optString(Const.DISTANCE));

                        String start = jsonObject.optString(Const.START_TIME);
                        pcBean.pickTime = Helper.getFormattedDate1(start);

                        String end = jsonObject.optString(Const.END_TIME);
                        pcBean.dropTime = Helper.getFormattedDate1(end);

                        long millis = pcBean.dropTime - pcBean.pickTime;
                        pcBean.timeTaken = TimeUnit.MILLISECONDS.toMinutes(millis);

                        pcBean.rate = jsonObject.optString(Const.RATE);
                        pcBean.amount = Float.parseFloat(jsonObject.optString(Const.PRICE));

                        pcBean.orderId = jsonObject.optString("transactionId2");
                        pcBean.numberOfSeat = jsonObject.optString(Const.NUMBER_OF_SEATS);
                        pcBean.isPaymentSuccess = jsonObject.optBoolean("isPaymentSuccess");

                        gotoPaymentDetailsFragment();
                        break;
                    case "10":
                        name = jsonObject.optString(Const.NAME);
                        age = jsonObject.optString(Const.AGE);
                        eta = jsonObject.optString(Const.ETA);
                        mobile = jsonObject.optString(Const.MOBILE);
                        userId = jsonObject.optString(Const.USERID);
                        updateETA();
                        break;
                    case "20": //R2O
                        liftId = jsonObject.optString(Const.LIFT_ID);
                        offererId = jsonObject.optString(Const.USERID);
                        requesterId = Const.getUserId(activity);
                        action = "1";
                        if (validate()) {
                            networkHit();
                        }
                        break;
                    case "21":
                        updateTracker.updateLocationOnMap(jsonObject);
                        break;
                    case "chat":
                        String chatUser = jsonObject.optString(FireConst.SENDER_ID);
                        Intent intent = new Intent(activity, ChatActivity.class);
                        intent.putExtra(FireConst.CHAT_WITH_USER, chatUser);
                        startActivity(intent);
                        break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

}