diff --git a/Complete code/BornToCode.iml b/Complete code/BornToCode.iml new file mode 100644 index 0000000..29169eb --- /dev/null +++ b/Complete code/BornToCode.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Complete code/CabBookingDriver.iml b/Complete code/CabBookingDriver.iml new file mode 100644 index 0000000..0f8d69f --- /dev/null +++ b/Complete code/CabBookingDriver.iml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Complete code/README.md b/Complete code/README.md new file mode 100644 index 0000000..e69de29 diff --git a/Complete code/app/.gitignore b/Complete code/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/Complete code/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/Complete code/app/app.iml b/Complete code/app/app.iml new file mode 100644 index 0000000..76c28b6 --- /dev/null +++ b/Complete code/app/app.iml @@ -0,0 +1,277 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Complete code/app/build.gradle b/Complete code/app/build.gradle new file mode 100644 index 0000000..1a2e1e7 --- /dev/null +++ b/Complete code/app/build.gradle @@ -0,0 +1,53 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 26 + defaultConfig { + applicationId "com.softup.utkarsh.uber" + minSdkVersion 19 + targetSdkVersion 26 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + multiDexEnabled true + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation 'com.android.support:appcompat-v7:26.1.0' + implementation 'com.android.support.constraint:constraint-layout:1.1.0' + implementation 'com.google.android.gms:play-services-maps:12.0.1' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' + implementation 'com.google.firebase:firebase-core:12.0.1' + + //Add Library + implementation 'com.google.maps.android:android-maps-utils:0.5+' + implementation 'de.hdodenhof:circleimageview:2.2.0' + implementation 'com.squareup.picasso:picasso:2.5.2' + implementation 'com.squareup.retrofit2:retrofit:2.3.0' + implementation 'com.squareup.retrofit2:converter-scalars:2.3.0' + implementation 'com.squareup.retrofit2:converter-gson:2.3.0' + implementation 'com.github.glomadrian:MaterialAnimatedSwitch:1.1@aar' + implementation 'com.firebase:geofire-android:2.1.2' + implementation 'com.github.d-max:spots-dialog:0.7@aar' + implementation 'uk.co.chrisjenx:calligraphy:2.3.0' + implementation 'com.rengwuxian.materialedittext:library:2.1.4' + implementation 'com.android.support:design:26.+' + implementation 'com.android.support:cardview-v7:26.+' + implementation 'com.google.firebase:firebase-messaging:12.0.1' + implementation 'com.google.firebase:firebase-database:12.0.1' + implementation 'com.google.firebase:firebase-auth:12.0.1' + implementation 'com.google.android.gms:play-services:12.0.1' + implementation 'com.android.support:multidex:1.0.3' + +} +apply plugin: 'com.google.gms.google-services' diff --git a/Complete code/app/google-services.json b/Complete code/app/google-services.json new file mode 100644 index 0000000..bb62d3a --- /dev/null +++ b/Complete code/app/google-services.json @@ -0,0 +1,55 @@ +{ + "project_info": { + "project_number": "21625424728", + "firebase_url": "https://uber-798e0.firebaseio.com", + "project_id": "uber-798e0", + "storage_bucket": "uber-798e0.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:21625424728:android:366153b4406cffb8", + "android_client_info": { + "package_name": "com.softup.utkarsh.uber" + } + }, + "oauth_client": [ + { + "client_id": "21625424728-1q85m5dvv7pesadams64ti492a6flfc6.apps.googleusercontent.com", + "client_type": 1, + "android_info": { + "package_name": "com.softup.utkarsh.uber", + "certificate_hash": "e620ca98dc64d4a59cc867cccb87ee6e0913abf5" + } + }, + { + "client_id": "21625424728-fhujpkrdkte2g7rucdkjoqvgcdtick8l.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyD1EUcJZ2OFQ3habqilOdfo2grbguSmO18" + } + ], + "services": { + "analytics_service": { + "status": 1 + }, + "appinvite_service": { + "status": 2, + "other_platform_oauth_client": [ + { + "client_id": "21625424728-fhujpkrdkte2g7rucdkjoqvgcdtick8l.apps.googleusercontent.com", + "client_type": 3 + } + ] + }, + "ads_service": { + "status": 2 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/Complete code/app/proguard-rules.pro b/Complete code/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/Complete code/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/Complete code/app/src/androidTest/java/com/softup/utkarsh/uber/ExampleInstrumentedTest.java b/Complete code/app/src/androidTest/java/com/softup/utkarsh/uber/ExampleInstrumentedTest.java new file mode 100644 index 0000000..bc72bb4 --- /dev/null +++ b/Complete code/app/src/androidTest/java/com/softup/utkarsh/uber/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.softup.utkarsh.uber; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("com.softup.utkarsh.uber", appContext.getPackageName()); + } +} diff --git a/Complete code/app/src/debug/res/values/google_maps_api.xml b/Complete code/app/src/debug/res/values/google_maps_api.xml new file mode 100644 index 0000000..ee1ad08 --- /dev/null +++ b/Complete code/app/src/debug/res/values/google_maps_api.xml @@ -0,0 +1,26 @@ + + + + AIzaSyCGBMKqJny_m658EFB-42vAaYKxOdpoJXI + + diff --git a/Complete code/app/src/main/AndroidManifest.xml b/Complete code/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..6ded73a --- /dev/null +++ b/Complete code/app/src/main/AndroidManifest.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Complete code/app/src/main/assets/fonts/Arkhip_font.ttf b/Complete code/app/src/main/assets/fonts/Arkhip_font.ttf new file mode 100644 index 0000000..837bc86 Binary files /dev/null and b/Complete code/app/src/main/assets/fonts/Arkhip_font.ttf differ diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Common/Common.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Common/Common.java new file mode 100644 index 0000000..8864628 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Common/Common.java @@ -0,0 +1,46 @@ +package com.softup.utkarsh.uber.Common; + +import android.location.Location; + +import com.softup.utkarsh.uber.Model.User; +import com.softup.utkarsh.uber.Remote.FCMClient; +import com.softup.utkarsh.uber.Remote.IFCMService; +import com.softup.utkarsh.uber.Remote.IGoogleAPI; +import com.softup.utkarsh.uber.Remote.RetrofitClient; + +public class Common +{ + + public static final String driver_tb1 = "Drivers"; + public static final String user_driver_tb1 = "DriversInformation"; + public static final String user_rider_tb1 = "RidersInformation"; + public static final String pickup_request_tb1 = "PickupRequest"; + public static final String token_tb1 = "Tokens"; + public static final int PICK_IMAGE_REQUEST = 9999 ; + + public static User currentUser; + + public static Location mLastLocation=null; + + public static final String baseURL = "https://maps.googleapis.com"; + public static final String fcmURL = "https://fcm.googleapis.com/"; + + public static double base_fare = 1.00; + private static double time_rate = 0.00; + private static double distance_rate = 1.00; + + public static double formulaPrice(double km,double min) + { + return base_fare+(distance_rate*km)+(time_rate*min); + } + + public static IGoogleAPI getGoogleAPI() + { + return RetrofitClient.getClient(baseURL).create(IGoogleAPI.class); + } + + public static IFCMService getFCMService() + { + return FCMClient.getClient(fcmURL).create(IFCMService.class); + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/CustommerCall.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/CustommerCall.java new file mode 100644 index 0000000..ff2ee59 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/CustommerCall.java @@ -0,0 +1,214 @@ +package com.softup.utkarsh.uber; + +import android.animation.ValueAnimator; +import android.content.Intent; +import android.graphics.Color; +import android.media.MediaPlayer; +import android.os.Handler; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.view.animation.LinearInterpolator; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.android.gms.maps.CameraUpdate; +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.model.BitmapDescriptorFactory; +import com.google.android.gms.maps.model.JointType; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.LatLngBounds; +import com.google.android.gms.maps.model.MarkerOptions; +import com.google.android.gms.maps.model.PolylineOptions; +import com.google.android.gms.maps.model.SquareCap; +import com.softup.utkarsh.uber.Common.Common; +import com.softup.utkarsh.uber.Model.FCMResponse; +import com.softup.utkarsh.uber.Model.Notification; +import com.softup.utkarsh.uber.Model.Sender; +import com.softup.utkarsh.uber.Model.Token; +import com.softup.utkarsh.uber.Remote.IFCMService; +import com.softup.utkarsh.uber.Remote.IGoogleAPI; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.List; + +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +public class CustommerCall extends AppCompatActivity { + + TextView txtTime,txtAddress,txtDistance; + Button btnCancel,btnAccept; + + MediaPlayer mediaPlayer; + + IGoogleAPI mService; + IFCMService mFCMService; + + String customerId; + + double lat,lng; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_custommer_call); + + mService = Common.getGoogleAPI(); + mFCMService = Common.getFCMService(); + + //InitView + txtAddress = (TextView) findViewById(R.id.txtAddress); + txtDistance = (TextView) findViewById(R.id.txtDistance); + txtTime = (TextView) findViewById(R.id.txtTime); + + btnAccept = (Button)findViewById(R.id.btnAccept); + btnCancel = (Button)findViewById(R.id.btnDecline); + + btnCancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (!TextUtils.isEmpty(customerId)) + cancelBooking(customerId); + + } + }); + + btnAccept.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(CustommerCall.this,DriverTracking.class); + intent.putExtra("lat",lat); + intent.putExtra("lng",lng); + intent.putExtra("customerId",customerId); + + startActivity(intent); + finish(); + } + }); + + mediaPlayer = MediaPlayer.create(this,R.raw.ringtone); + mediaPlayer.setLooping(true); + mediaPlayer.start(); + + if (getIntent() != null) + { + lat = getIntent().getDoubleExtra("lat",-1.0); + lng = getIntent().getDoubleExtra("lng",-1.0); + customerId = getIntent().getStringExtra("customer"); + + //Just copy getDirection from Welcome Activity + getDirection(lat,lng); + + } + + } + + private void cancelBooking(String customerId) { + Token token = new Token(customerId); + + Notification notification = new Notification("Cancel", "Driver has cancelled your request"); + Sender sender = new Sender(token.getToken(),notification); + + mFCMService.sendMessage(sender) + .enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + if (response.body().success == 1) + { + Toast.makeText(CustommerCall.this, "Cancelled", Toast.LENGTH_SHORT).show(); + finish(); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + } + + private void getDirection(double lat, double lng) { + + + String requestApi = null; + try { + requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+ + "mode=driving&"+ + "transit_routing_preference=less_driving&"+ + "origin="+ Common.mLastLocation.getLatitude()+","+Common.mLastLocation.getLongitude()+"&"+ + "destination="+lat+","+lng+"&"+ + "key="+getResources().getString(R.string.google_direction_api); + Log.d("UBER",requestApi); //Print URL for debug + mService.getPath(requestApi) + .enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + + try { + JSONObject jsonObject = new JSONObject(response.body().toString()); + + JSONArray routes = jsonObject.getJSONArray("routes"); + + JSONObject object = routes.getJSONObject(0); + + JSONArray legs = object.getJSONArray("legs"); + + JSONObject legsObject = legs.getJSONObject(0); + + JSONObject distance = legsObject.getJSONObject("distance"); + txtDistance.setText(distance.getString("text")); + + + JSONObject time = legsObject.getJSONObject("duration"); + txtTime.setText(time.getString("text")); + + + String address = legsObject.getString("end_address"); + txtAddress.setText(address); + + + } catch (JSONException e) { + e.printStackTrace(); + } + + } + + @Override + public void onFailure(Call call, Throwable t) { + Toast.makeText(CustommerCall.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + + }catch (Exception e) + { + e.printStackTrace(); + } + } + + @Override + protected void onStop() { + mediaPlayer.release(); + super.onStop(); + } + + @Override + protected void onPause() { + mediaPlayer.release(); + super.onPause(); + } + + @Override + protected void onPostResume() { + + super.onPostResume(); + mediaPlayer.start(); + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/DriverHome.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/DriverHome.java new file mode 100644 index 0000000..3b45eb5 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/DriverHome.java @@ -0,0 +1,1209 @@ +package com.softup.utkarsh.uber; + +import android.Manifest; +import android.animation.ValueAnimator; +import android.annotation.SuppressLint; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.Resources; +import android.graphics.Color; +import android.location.Location; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.design.widget.FloatingActionButton; +import android.support.design.widget.Snackbar; +import android.support.v4.app.ActivityCompat; +import android.support.v7.app.AlertDialog; +import android.text.TextUtils; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.support.design.widget.NavigationView; +import android.support.v4.view.GravityCompat; +import android.support.v4.widget.DrawerLayout; +import android.support.v7.app.ActionBarDrawerToggle; +import android.support.v7.app.AppCompatActivity; +import android.support.v7.widget.Toolbar; +import android.view.Menu; +import android.view.MenuItem; +import android.view.animation.LinearInterpolator; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import com.firebase.geofire.GeoFire; +import com.firebase.geofire.GeoLocation; +import com.github.glomadrian.materialanimatedswitch.MaterialAnimatedSwitch; +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GooglePlayServicesUtil; +import com.google.android.gms.common.api.GoogleApiClient; +import com.google.android.gms.common.api.Status; +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.places.AutocompleteFilter; +import com.google.android.gms.location.places.Place; +import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment; +import com.google.android.gms.location.places.ui.PlaceSelectionListener; +import com.google.android.gms.maps.CameraUpdate; +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.OnMapReadyCallback; +import com.google.android.gms.maps.SupportMapFragment; +import com.google.android.gms.maps.model.BitmapDescriptorFactory; +import com.google.android.gms.maps.model.CameraPosition; +import com.google.android.gms.maps.model.JointType; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.LatLngBounds; +import com.google.android.gms.maps.model.MapStyleOptions; +import com.google.android.gms.maps.model.Marker; +import com.google.android.gms.maps.model.MarkerOptions; +import com.google.android.gms.maps.model.Polyline; +import com.google.android.gms.maps.model.PolylineOptions; +import com.google.android.gms.maps.model.SquareCap; +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.android.gms.tasks.Task; +import com.google.firebase.auth.AuthCredential; +import com.google.firebase.auth.EmailAuthProvider; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.ValueEventListener; +import com.google.firebase.iid.FirebaseInstanceId; +import com.google.firebase.storage.FirebaseStorage; +import com.google.firebase.storage.OnProgressListener; +import com.google.firebase.storage.StorageReference; +import com.google.firebase.storage.UploadTask; +import com.google.maps.android.SphericalUtil; +import com.rengwuxian.materialedittext.MaterialEditText; +import com.softup.utkarsh.uber.Common.Common; +import com.softup.utkarsh.uber.Model.Token; +import com.softup.utkarsh.uber.Model.User; +import com.softup.utkarsh.uber.Remote.IGoogleAPI; +import com.squareup.picasso.Picasso; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import de.hdodenhof.circleimageview.CircleImageView; +import dmax.dialog.SpotsDialog; +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +public class DriverHome extends AppCompatActivity + implements NavigationView.OnNavigationItemSelectedListener, + OnMapReadyCallback, + GoogleApiClient.ConnectionCallbacks, + GoogleApiClient.OnConnectionFailedListener, + LocationListener + + +{ + + private GoogleMap mMap; + Context context; + + //Play Services + private static final int MY_PERMISSION_REQUEST_CODE = 7000; + private static final int PLAY_SERVICE_RES_REQUEST = 7001; + + private LocationRequest mLocationRequest; + private GoogleApiClient mGoogleApiClient; + + + private static int UPDATE_INTERVAL = 5000; + private static int FATEST_INTERVAL = 3000; + private static int DISPLACEMENT = 10; + + DatabaseReference drivers; + GeoFire geoFire; + + Marker mCurrent; + + MaterialAnimatedSwitch location_switch; + SupportMapFragment mapFragment; + + + //Car animation + private List polyLineList; + private Marker carMarker; + private float v; + private double lat,lng; + private Handler handler; + private LatLng startPostion, endPosition,currentPosition; + private int index,next; + // private Button btnGo; + private PlaceAutocompleteFragment places; + AutocompleteFilter typeFilter; + private String destination; + private PolylineOptions polylineOptions,blackPolylineOptions; + private Polyline blackPolyline,greyPolyline; + + private IGoogleAPI mService; + + //Presense System + DatabaseReference onlineRef,currentUserRef; + + //Firebase Storage + FirebaseStorage firebaseStorage; + StorageReference storageReference; + + Runnable drawPathRunnable= new Runnable() { + @Override + public void run() { + if (index= endPosition.latitude && startPostion.longitude < endPosition.longitude) + return (float)((90-Math.toDegrees(Math.atan(lng/lat)))+90); + else if (startPostion.latitude >= endPosition.latitude && startPostion.longitude >= endPosition.longitude) + return (float)(Math.toDegrees(Math.atan(lng/lat))+180); + else if (startPostion.latitude < endPosition.latitude && startPostion.longitude >= endPosition.longitude) + return (float)((90-Math.toDegrees(Math.atan(lng/lat)))+270); + return -1; + + } + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_driver_home); + Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); + + //Init Firebase Storage + firebaseStorage = FirebaseStorage.getInstance(); + storageReference = firebaseStorage.getReference(); + + + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( + this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); + drawer.addDrawerListener(toggle); + toggle.syncState(); + + NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); + navigationView.setNavigationItemSelectedListener(this); + + View navigationHeaderView = navigationView.getHeaderView(0); + final TextView txtName = (TextView)navigationHeaderView.findViewById(R.id.txtDriverName); + final TextView txtStars = (TextView)navigationHeaderView.findViewById(R.id.txtStars); + + CircleImageView imageAvatar = (CircleImageView) navigationHeaderView.findViewById(R.id.image_avatar); + + txtName.setText(Common.currentUser.getName()); + txtStars.setText(Common.currentUser.getRates()); + + + + if (Common.currentUser.getAvatarUrl() != null && !TextUtils.isEmpty(Common.currentUser.getAvatarUrl())) { + Picasso.with(this) + .load(Common.currentUser.getAvatarUrl()) + .into(imageAvatar); + + } + + drawer.addDrawerListener(new DrawerLayout.DrawerListener() { + + @Override + public void onDrawerSlide(View drawerView, float slideOffset) { + //Called when a drawer's position changes. + + } + + @Override + public void onDrawerOpened(View drawerView) { + //Called when a drawer has settled in a completely open state. + //The drawer is interactive at this point. + // If you have 2 drawers (left and right) you can distinguish + // them by using id of the drawerView. int id = drawerView.getId(); + // id will be your layout's id: for example R.id.left_drawer + DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + DatabaseReference uidRef = rootRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()); + ValueEventListener valueEventListener = new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + // String userEmail = dataSnapshot.child("userEmail").getValue(String.class); + // String userID = dataSnapshot.child("userID").getValue(String.class); + String userName = dataSnapshot.child("rates").getValue(String.class); + //String userUsername = dataSnapshot.child("userUsername").getValue(String.class); + //Log.d("TAG", userEmail + " / " + userID + " / " + userName + " / " + userUsername); + Common.currentUser.setRates(userName); + txtStars.setText(userName); + + } + + @Override + public void onCancelled(DatabaseError databaseError) {} + }; + uidRef.addListenerForSingleValueEvent(valueEventListener); + } + + @Override + public void onDrawerClosed(View drawerView) { + // Called when a drawer has settled in a completely closed state. + } + + @Override + public void onDrawerStateChanged(int newState) { + // Called when the drawer motion state changes. The new state will be one of STATE_IDLE, STATE_DRAGGING or STATE_SETTLING. + + + } + }); + + + // DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + //driverInformations.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + + /* DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + DatabaseReference uidRef = rootRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()); + ValueEventListener valueEventListener = new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + // String userEmail = dataSnapshot.child("userEmail").getValue(String.class); + // String userID = dataSnapshot.child("userID").getValue(String.class); + String userName = dataSnapshot.child("name").getValue(String.class); + //String userUsername = dataSnapshot.child("userUsername").getValue(String.class); + //Log.d("TAG", userEmail + " / " + userID + " / " + userName + " / " + userUsername); + txtName.setText(userName); + } + + @Override + public void onCancelled(DatabaseError databaseError) {} + }; + uidRef.addListenerForSingleValueEvent(valueEventListener); */ + + + + + //Paste here + // Obtain the SupportMapFragment and get notified when the map is ready to be used. + mapFragment = (SupportMapFragment) getSupportFragmentManager() + .findFragmentById(R.id.map); + mapFragment.getMapAsync(this); + + //Presence System + onlineRef = FirebaseDatabase.getInstance().getReference().child(".info/connected"); + currentUserRef = FirebaseDatabase.getInstance().getReference(Common.driver_tb1) + .child(FirebaseAuth.getInstance().getCurrentUser().getUid()); + onlineRef.addValueEventListener(new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + //We will remove value from Driver tb1 when driver is disconnected + currentUserRef.onDisconnect().removeValue(); + } + + @Override + public void onCancelled(DatabaseError databaseError) { + + } + }); + + //Init View + location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch); + location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(boolean isOnline) { + if (isOnline) { + FirebaseDatabase.getInstance().goOnline(); //set connected when switch to on + startLocationUpdates(); + displayLocation(); + Snackbar.make(mapFragment.getView(), "You are online", Snackbar.LENGTH_SHORT) + .show(); + } else { + + FirebaseDatabase.getInstance().goOffline(); //Set disconnected when switch to off + + stopLocationUpdates(); + mCurrent.remove(); + mMap.clear(); + if(handler != null) + handler.removeCallbacks(drawPathRunnable); + Snackbar.make(mapFragment.getView(), "You are offline", Snackbar.LENGTH_SHORT) + .show(); + } + + } + }); + + polyLineList = new ArrayList<>(); + + + //Places API + typeFilter = new AutocompleteFilter.Builder() + .setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS) + .setTypeFilter(3) + .build(); + places = (PlaceAutocompleteFragment) getFragmentManager(). findFragmentById(R.id.place_autocomplete_fragment); + places.setOnPlaceSelectedListener(new PlaceSelectionListener() { + @Override + public void onPlaceSelected(Place place) { + if(location_switch.isChecked()) + { + destination = place.getAddress().toString(); + destination = destination.replace(" ","+"); + + getDirection(); + } + else + { + Toast.makeText(DriverHome.this, "Please change your status to ONLINE", Toast.LENGTH_SHORT).show(); + } + + } + + @Override + public void onError(Status status) { + Toast.makeText(DriverHome.this, ""+status.toString(), Toast.LENGTH_SHORT).show(); + + } + }); + + + + // Geo Fire + drivers = FirebaseDatabase.getInstance().getReference(Common.driver_tb1); + geoFire = new GeoFire(drivers); + + setUpLocation(); + + mService = Common.getGoogleAPI(); + + updateFirebaseToken(); + + + + } + + + + private void updateFirebaseToken() { + FirebaseDatabase db = FirebaseDatabase.getInstance(); + DatabaseReference tokens = db.getReference(Common.token_tb1); + + Token token = new Token(FirebaseInstanceId.getInstance().getToken()); + tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .setValue(token); + } + + private void getDirection() { + currentPosition = new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude()); + + String requestApi = null; + try { + requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+ + "mode=driving&"+ + "transit_routing_preference=less_driving&"+ + "origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+ + "destination="+destination+"&"+ + "key="+getResources().getString(R.string.google_direction_api); + Log.d("UBER",requestApi); //Print URL for debug + mService.getPath(requestApi) + .enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + + try { + JSONObject jsonObject = new JSONObject(response.body().toString()); + JSONArray jsonArray = jsonObject.getJSONArray("routes"); + for (int i=0;i points = greyPolyline.getPoints(); + int percentValue = (int)valueAnimator.getAnimatedValue(); + int size = points.size(); + int newPoints = (int) (size * (percentValue/100.0f)); + List p = points.subList(0,newPoints); + blackPolyline.setPoints(p); + } + }); + + polyLineAnimator.start(); + + carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition) + .flat(true) + .icon(BitmapDescriptorFactory.fromResource(R.drawable.car))); + + handler = new Handler(); + index=-1; + next=1; + handler.postDelayed(drawPathRunnable,3000); + + } catch (JSONException e) { + e.printStackTrace(); + } + + } + + @Override + public void onFailure(Call call, Throwable t) { + Toast.makeText(DriverHome.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + + }catch (Exception e) + { + e.printStackTrace(); + } + + } + + /** + * Method to decode polyline points + * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java + * */ + private List decodePoly(String encoded) { + + List poly = new ArrayList(); + int index = 0, len = encoded.length(); + int lat = 0, lng = 0; + + while (index < len) { + int b, shift = 0, result = 0; + do { + b = encoded.charAt(index++) - 63; + result |= (b & 0x1f) << shift; + shift += 5; + } while (b >= 0x20); + int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); + lat += dlat; + + shift = 0; + result = 0; + do { + b = encoded.charAt(index++) - 63; + result |= (b & 0x1f) << shift; + shift += 5; + } while (b >= 0x20); + int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); + lng += dlng; + + LatLng p = new LatLng((((double) lat / 1E5)), + (((double) lng / 1E5))); + poly.add(p); + } + + return poly; + } + + //Press Ctrl+O + //Because we request runtime permission, we need to override OnRequestPermissionResult methord + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + switch (requestCode) + { + case MY_PERMISSION_REQUEST_CODE: + if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) + { + if (checkPlayServices()) + { + buildGoogleApiClient(); + createLocationRequest(); + if (location_switch.isChecked()) + { + displayLocation(); + } + } + } + } + } + + private void setUpLocation() { + if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) + { + // Request runtime permission + ActivityCompat.requestPermissions(this, new String[]{ + android.Manifest.permission.ACCESS_COARSE_LOCATION, + android.Manifest.permission.ACCESS_FINE_LOCATION + + },MY_PERMISSION_REQUEST_CODE); + } + else + { + if (checkPlayServices()) + { + buildGoogleApiClient(); + createLocationRequest(); + if (location_switch.isChecked()) + { + displayLocation(); + } + } + } + + } + + + @SuppressLint("RestrictedApi") + private void createLocationRequest() { + mLocationRequest = new LocationRequest(); + mLocationRequest.setInterval(UPDATE_INTERVAL); + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void buildGoogleApiClient() { + mGoogleApiClient = new GoogleApiClient.Builder(this) + .addConnectionCallbacks(this) + .addOnConnectionFailedListener(this) + .addApi(LocationServices.API) + .build(); + mGoogleApiClient.connect(); + } + + private boolean checkPlayServices() { + int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); + if (resultCode != ConnectionResult.SUCCESS) + { + if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) + GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICE_RES_REQUEST).show(); + else { + Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show(); + finish(); + } + return false; + } + return true; + } + + private void stopLocationUpdates() { + if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) + { + return; + } + LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this); + } + + private void displayLocation() { + if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) + { + return; + } + Common.mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); + if(Common.mLastLocation != null) + { + if (location_switch.isChecked()) + { + final double latitude = Common.mLastLocation.getLatitude(); + final double longitude = Common.mLastLocation.getLongitude(); + + LatLng center = new LatLng(latitude,longitude); + LatLng northSide = SphericalUtil.computeOffset(center,100000,0); + LatLng southSide = SphericalUtil.computeOffset(center,100000,180); + + LatLngBounds bounds = LatLngBounds.builder() + .include(northSide) + .include(southSide) + .build(); + places.setBoundsBias(bounds); + places.setFilter(typeFilter); + + //Update to Firebase + geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() { + @Override + public void onComplete(String key, DatabaseError error) { + //Add Marker + if (mCurrent != null) + mCurrent.remove(); //Remove already marker + mCurrent = mMap.addMarker(new MarkerOptions() + + .position(new LatLng(latitude,longitude)) + .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)) + .title("Your Location")); + + //Move camera to this position + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),15.0f)); + + } + }); + } + } + else + { + Log.d("Error","Cannot get your location"); + } + } + + + + private void startLocationUpdates() { + if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) + { + return; + } + LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this); + } + + @Override + public void onBackPressed() { + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + if (drawer.isDrawerOpen(GravityCompat.START)) { + drawer.closeDrawer(GravityCompat.START); + } else { + super.onBackPressed(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.driver_home, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + + + + return super.onOptionsItemSelected(item); + } + + @SuppressWarnings("StatementWithEmptyBody") + @Override + public boolean onNavigationItemSelected(MenuItem item) { + // Handle navigation view item clicks here. + int id = item.getItemId(); + + if (id == R.id.nav_trip_history) { + // Handle the camera action + } else if (id == R.id.nav_way_bill) { + + } else if (id == R.id.nav_help) { + + } else if (id == R.id.nav_sign_out) { + signOut(); + + } else if (id == R.id.nav_settings) { + + } + else if (id == R.id.nav_update_info) { + showDialogUpdateInfo(); + + } + else if (id == R.id.nav_change_pwd) { + showDialogChangePwd(); + + } + DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); + drawer.closeDrawer(GravityCompat.START); + return true; + } + + private void showDialogUpdateInfo() { + AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this); + alertDialog.setTitle("UPDATE PHOTO"); + alertDialog.setMessage("Please your Photo"); + LayoutInflater inflater = this.getLayoutInflater(); + View layout_pwd = inflater.inflate(R.layout.layout_update_information,null); + final MaterialEditText edtName = (MaterialEditText)layout_pwd.findViewById(R.id.edtName); + final MaterialEditText edtPhone = (MaterialEditText)layout_pwd.findViewById(R.id.edtPhone); + final ImageView image_upload = (ImageView) layout_pwd.findViewById(R.id.image_upload); + image_upload.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + chooseImage(); + + } + }); + + alertDialog.setView(layout_pwd); + + //Set Button + alertDialog.setPositiveButton("", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + final android.app.AlertDialog waitingDialog = new SpotsDialog(DriverHome.this); + waitingDialog.show(); + + String name = edtName.getText().toString(); + String phone = edtPhone.getText().toString(); + Map updateInfo = new HashMap<>(); + if (!TextUtils.isEmpty(name)) + updateInfo.put("name",name); + if (!TextUtils.isEmpty(phone)) + updateInfo.put("phone",phone); + + DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + driverInformations.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .updateChildren(updateInfo) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + // startActivity(getIntent()); + // finish(); + NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); + + View navigationHeaderView = navigationView.getHeaderView(0); + final TextView txtName = (TextView)navigationHeaderView.findViewById(R.id.txtDriverName); + //txtName.setText(Common.currentUser.getName()); + DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + DatabaseReference uidRef = rootRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()); + ValueEventListener valueEventListener = new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + // String userEmail = dataSnapshot.child("userEmail").getValue(String.class); + // String userID = dataSnapshot.child("userID").getValue(String.class); + String userName = dataSnapshot.child("name").getValue(String.class); + //String userUsername = dataSnapshot.child("userUsername").getValue(String.class); + //Log.d("TAG", userEmail + " / " + userID + " / " + userName + " / " + userUsername); + txtName.setText(userName); + } + + @Override + public void onCancelled(DatabaseError databaseError) {} + }; + uidRef.addListenerForSingleValueEvent(valueEventListener); + + Toast.makeText(DriverHome.this, "Information Updated ! !", Toast.LENGTH_SHORT).show(); + + } + else + Toast.makeText(DriverHome.this, "Information Update Failed !", Toast.LENGTH_SHORT).show(); + waitingDialog.dismiss(); + } + }); + + + + } + }); + + alertDialog.setNegativeButton("BACK", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + + alertDialog.show(); + + } + + private void chooseImage() { + Intent intent = new Intent(); + intent.setType("image/*"); + intent.setAction(Intent.ACTION_GET_CONTENT); + startActivityForResult(Intent.createChooser(intent,"Select Picture: "),Common.PICK_IMAGE_REQUEST); + + } + + /* @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode == Common.PICK_IMAGE_REQUEST && requestCode == RESULT_OK + && data !=null && data.getData() !=null) + { + Uri saveUri = data.getData(); + if (saveUri !=null) + { + final ProgressDialog mDialog = new ProgressDialog(this); + mDialog.setMessage("Uploading..."); + mDialog.show(); + + String imageName = UUID.randomUUID().toString(); //Random name image upload + final StorageReference imageFolder = storageReference.child("images/"+imageName); + imageFolder.putFile(saveUri) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { + mDialog.dismiss(); + // Toast.makeText(DriverHome.this, "Uploaded !", Toast.LENGTH_SHORT).show(); + imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Uri uri) { + Map avatarUpdate = new HashMap<>(); + avatarUpdate.put("avatarUrl",uri.toString()); + DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + driverInformations.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .updateChildren(avatarUpdate) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) + Toast.makeText(DriverHome.this, "Uploaded !", Toast.LENGTH_SHORT).show(); + else + Toast.makeText(DriverHome.this, "Upload error !", Toast.LENGTH_SHORT).show(); + } + }); + + + } + }); + + } + }) + .addOnProgressListener(new OnProgressListener() { + @Override + public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { + double progress = (100.0* taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); + mDialog.setMessage("Uploaded"+progress+"%"); + } + }); + + + } + } + } */ + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode != RESULT_OK) { + return; + } + if (requestCode == Common.PICK_IMAGE_REQUEST && requestCode == RESULT_OK + && data !=null && data.getData() !=null); + { + Uri saveUri = data.getData(); + if (saveUri != null) + { + final ProgressDialog mDialog = new ProgressDialog(this); + mDialog.setMessage("Uploading..."); + mDialog.show(); + + String imageName = UUID.randomUUID().toString(); //Random name image upload + final StorageReference imageFolder = storageReference.child("images/"+imageName); + imageFolder.putFile(saveUri) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { + mDialog.dismiss(); + // Toast.makeText(Home.this, "Uploaded", Toast.LENGTH_SHORT).show(); + imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Uri uri) { + String s = getIntent().getStringExtra("EXTRA_SESSION_ID"); + + //Update this url to avatar property of User + Map AvatarUpdate = new HashMap<>(); + AvatarUpdate.put("avatarUrl",uri.toString()); + + DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + driverInformations.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .updateChildren(AvatarUpdate) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); + View navigationHeaderView = navigationView.getHeaderView(0); + final CircleImageView imageAvatar = (CircleImageView) navigationHeaderView.findViewById(R.id.image_avatar); + + DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + DatabaseReference uidRef = rootRef.child(FirebaseAuth.getInstance().getCurrentUser().getUid()); + ValueEventListener valueEventListener = new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + // String userEmail = dataSnapshot.child("userEmail").getValue(String.class); + // String userID = dataSnapshot.child("userID").getValue(String.class); + String userName = dataSnapshot.child("avatarUrl").getValue(String.class); + //String userUsername = dataSnapshot.child("userUsername").getValue(String.class); + //Log.d("TAG", userEmail + " / " + userID + " / " + userName + " / " + userUsername); + // txtName.setText(userName); + if (Common.currentUser.getAvatarUrl() != null && !TextUtils.isEmpty(Common.currentUser.getAvatarUrl())) { + + Picasso.with(context) + .load(userName) + .into(imageAvatar); + } + } + + @Override + public void onCancelled(DatabaseError databaseError) {} + }; + uidRef.addListenerForSingleValueEvent(valueEventListener); + + Toast.makeText(DriverHome.this, "Uploaded", Toast.LENGTH_SHORT).show(); + + } + else { + Toast.makeText(DriverHome.this, "Upload error", Toast.LENGTH_SHORT).show(); + } + + } + }); + + + } + }); + + } + }) + .addOnProgressListener(new OnProgressListener() { + @Override + public void onProgress(UploadTask.TaskSnapshot taskSnapshot) { + double progress = (100.0* taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount()); + mDialog.setMessage("Uploaded"+progress+"%"); + + } + }); + + } + + } + + + } + + private void showDialogChangePwd() { + AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this); + alertDialog.setTitle("CHANGE PASSWORD"); + alertDialog.setMessage("Please fill all information"); + LayoutInflater inflater = this.getLayoutInflater(); + View layout_pwd = inflater.inflate(R.layout.layout_change_pwd,null); + final MaterialEditText edtPassword = (MaterialEditText)layout_pwd.findViewById(R.id.edtPassword); + final MaterialEditText edtNewPassword = (MaterialEditText)layout_pwd.findViewById(R.id.edtNewPassword); + final MaterialEditText edtRepeatPassword = (MaterialEditText)layout_pwd.findViewById(R.id.edtRepeatPassword); + + alertDialog.setView(layout_pwd); + + //Set Button + alertDialog.setPositiveButton("CHANGE PASSWORD", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + if (edtPassword.getText().toString().trim().length() == 0 || edtNewPassword.getText().toString().trim().length() == 0 || edtRepeatPassword.getText().toString().trim().length() == 0) + { + Toast.makeText(DriverHome.this, "Please enter all the fields !", Toast.LENGTH_SHORT).show(); + } + + + + else if (edtPassword.getText().toString().trim().length() > 0 && edtNewPassword.getText().toString().trim().length() > 0 && edtRepeatPassword.getText().toString().trim().length() > 0) + { + final android.app.AlertDialog waitingDialog = new SpotsDialog(DriverHome.this); + waitingDialog.show(); + if (edtNewPassword.getText().toString().equals(edtRepeatPassword.getText().toString())) { + String email = FirebaseAuth.getInstance().getCurrentUser().getEmail(); + + //Get auth credentials from the user for re-authentication. + //Example with only email + AuthCredential credential = EmailAuthProvider.getCredential(email, edtPassword.getText().toString()); + FirebaseAuth.getInstance().getCurrentUser() + .reauthenticate(credential) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + FirebaseAuth.getInstance().getCurrentUser() + .updatePassword(edtRepeatPassword.getText().toString()) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) { + //Update Driver information password column + Map password = new HashMap<>(); + + password.put("password", edtRepeatPassword.getText().toString()); + + DatabaseReference driverInformation = FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1); + + driverInformation.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .updateChildren(password) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + if (task.isSuccessful()) + Toast.makeText(DriverHome.this, "Password was changed !", Toast.LENGTH_SHORT).show(); + else + Toast.makeText(DriverHome.this, "Password was changed but not update to Driver Information", Toast.LENGTH_SHORT).show(); + waitingDialog.dismiss(); + } + }); + } else { + Toast.makeText(DriverHome.this, "Password should be atleast of 6 letters!", Toast.LENGTH_SHORT).show(); + waitingDialog.dismiss(); + } + } + }); + } else { + waitingDialog.dismiss(); + Toast.makeText(DriverHome.this, "Wrong old password", Toast.LENGTH_SHORT).show(); + } + } + }); + + } else { + waitingDialog.dismiss(); + Toast.makeText(DriverHome.this, "Password doesn't match", Toast.LENGTH_SHORT).show(); + } + } + + } + }); + alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + //Show Dialog + alertDialog.show(); + } + + private void signOut() { + FirebaseAuth.getInstance().signOut(); + Intent intent = new Intent(DriverHome.this,MainActivity.class); + startActivity(intent); + finish(); + + } + + @Override + public void onConnected(@Nullable Bundle bundle) { + displayLocation(); + startLocationUpdates(); + } + + @Override + public void onConnectionSuspended(int i) { + mGoogleApiClient.connect(); + } + + @Override + public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { + + } + + @Override + public void onLocationChanged(Location location) { + Common.mLastLocation = location; + displayLocation(); + } + + @Override + public void onMapReady(GoogleMap googleMap) { + try { + boolean isSuccess = googleMap.setMapStyle( + MapStyleOptions.loadRawResourceStyle(this, R.raw.uber_style_map) + ); + if (!isSuccess) + Log.e("ERROR","Map style load failed !!!"); + } + catch (Resources.NotFoundException ex) + { + ex.printStackTrace(); + } + + mMap = googleMap; + mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); + mMap.setTrafficEnabled(false); + mMap.setIndoorEnabled(false); + mMap.setBuildingsEnabled(false); + mMap.getUiSettings().setZoomControlsEnabled(true); + + + + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/DriverTracking.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/DriverTracking.java new file mode 100644 index 0000000..4e0b2f3 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/DriverTracking.java @@ -0,0 +1,545 @@ +package com.softup.utkarsh.uber; + +import android.Manifest; +import android.animation.ValueAnimator; +import android.annotation.SuppressLint; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.res.Resources; +import android.graphics.Color; +import android.location.Location; +import android.os.AsyncTask; +import android.os.Handler; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; +import android.support.v4.app.ActivityCompat; +import android.support.v4.app.FragmentActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.view.animation.LinearInterpolator; +import android.widget.Button; +import android.widget.Toast; + +import com.firebase.geofire.GeoFire; +import com.firebase.geofire.GeoLocation; +import com.firebase.geofire.GeoQuery; +import com.firebase.geofire.GeoQueryEventListener; +import com.google.android.gms.common.ConnectionResult; +import com.google.android.gms.common.GooglePlayServicesUtil; +import com.google.android.gms.common.api.GoogleApiClient; +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.maps.CameraUpdate; +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.OnMapReadyCallback; +import com.google.android.gms.maps.SupportMapFragment; +import com.google.android.gms.maps.model.BitmapDescriptorFactory; +import com.google.android.gms.maps.model.Circle; +import com.google.android.gms.maps.model.CircleOptions; +import com.google.android.gms.maps.model.JointType; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.LatLngBounds; +import com.google.android.gms.maps.model.MapStyleOptions; +import com.google.android.gms.maps.model.Marker; +import com.google.android.gms.maps.model.MarkerOptions; +import com.google.android.gms.maps.model.Polyline; +import com.google.android.gms.maps.model.PolylineOptions; +import com.google.android.gms.maps.model.SquareCap; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.FirebaseDatabase; +import com.softup.utkarsh.uber.Common.Common; +import com.softup.utkarsh.uber.Helper.DirectionJSONParser; +import com.softup.utkarsh.uber.Model.FCMResponse; +import com.softup.utkarsh.uber.Model.Notification; +import com.softup.utkarsh.uber.Model.Sender; +import com.softup.utkarsh.uber.Model.Token; +import com.softup.utkarsh.uber.Remote.IFCMService; +import com.softup.utkarsh.uber.Remote.IGoogleAPI; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import retrofit2.Call; +import retrofit2.Callback; +import retrofit2.Response; + +public class DriverTracking extends FragmentActivity implements OnMapReadyCallback, + GoogleApiClient.OnConnectionFailedListener, + GoogleApiClient.ConnectionCallbacks, + LocationListener{ + + private GoogleMap mMap; + + double riderLat,riderLng; + + String customerId; + + + private static final int PLAY_SERVICE_RES_REQUEST = 7001; + + private LocationRequest mLocationRequest; + private GoogleApiClient mGoogleApiClient; + + + private static int UPDATE_INTERVAL = 5000; + private static int FATEST_INTERVAL = 3000; + private static int DISPLACEMENT = 10; + + private Circle riderMarker; + private Marker driverMarker; + private Polyline direction; + + IGoogleAPI mService; + IFCMService mFCMService; + + GeoFire geoFire; + + Button btnStartTrip; + + Location pickupLocation; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_driver_tracking); + // Obtain the SupportMapFragment and get notified when the map is ready to be used. + SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() + .findFragmentById(R.id.map); + mapFragment.getMapAsync(this); + + if (getIntent() != null) + { + riderLat = getIntent().getDoubleExtra("lat",-1.0); + + riderLng = getIntent().getDoubleExtra("lng",-1.0); + customerId = getIntent().getStringExtra("customerId"); + } + + mService = Common.getGoogleAPI(); + mFCMService = Common.getFCMService(); + + setUpLocation(); + + btnStartTrip = (Button)findViewById(R.id.btnStartTrip); + btnStartTrip.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (btnStartTrip.getText().equals("START TRIP")) + { + pickupLocation=Common.mLastLocation; + btnStartTrip.setText("DROP OFF HERE"); + } + else if (btnStartTrip.getText().equals("DROP OFF HERE")) + { + calculateCashFee(pickupLocation,Common.mLastLocation); + } + } + }); + } + + private void calculateCashFee(final Location pickupLocation, Location mLastLocation) { + + String requestApi = null; + try { + requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+ + "mode=driving&"+ + "transit_routing_preference=less_driving&"+ + "origin="+pickupLocation.getLatitude()+","+pickupLocation.getLongitude()+"&"+ + "destination="+mLastLocation.getLatitude()+","+mLastLocation.getLongitude()+"&"+ + "key="+getResources().getString(R.string.google_direction_api); + + mService.getPath(requestApi) + .enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + + try { + //Extract JSON + //Root Object + JSONObject jsonObject = new JSONObject(response.body().toString()); + JSONArray routes = jsonObject.getJSONArray("routes"); + JSONObject object = routes.getJSONObject(0); + JSONArray legs = object.getJSONArray("legs"); + JSONObject legsObject = legs.getJSONObject(0); + + //Get Distance + JSONObject distance = legsObject.getJSONObject("distance"); + String distance_text = distance.getString("text"); + Double distance_value = Double.parseDouble(distance_text.replaceAll("[^0-9\\\\.]+","")); + + //Get Distance + JSONObject timeObject = legsObject.getJSONObject("duration"); + String time_text = timeObject.getString("text"); + Double time_value = Double.parseDouble(time_text.replaceAll("[^0-9\\\\.]+","")); + + sendDropOffNotification(customerId); + + //Now we need write function calculate fee base on barefee and distance + time + Intent intent = new Intent(DriverTracking.this,TripDetail.class); + intent.putExtra("start_address",legsObject.getString("start_address")); + intent.putExtra("end_address",legsObject.getString("end_address")); + intent.putExtra("time",String.valueOf(time_value)); + intent.putExtra("distance",String.valueOf(distance_value)); + intent.putExtra("total",Common.formulaPrice(distance_value,time_value)); + intent.putExtra("location_start",String.format("%f,%f",pickupLocation.getLatitude(),pickupLocation.getLongitude())); + intent.putExtra("location_end",String.format("%f,%f",Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude())); + startActivity(intent); + finish(); + + + + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Override + public void onFailure(Call call, Throwable t) { + Toast.makeText(DriverTracking.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + + }catch (Exception e) + { + e.printStackTrace(); + } + + + } + + private void setUpLocation() { + + if (checkPlayServices()) + { + buildGoogleApiClient(); + createLocationRequest(); + + + displayLocation(); + + } + } + + @SuppressLint("RestrictedApi") + private void createLocationRequest() { + mLocationRequest = new LocationRequest(); + mLocationRequest.setInterval(UPDATE_INTERVAL); + mLocationRequest.setFastestInterval(FATEST_INTERVAL); + mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); + mLocationRequest.setSmallestDisplacement(DISPLACEMENT); + } + + private void buildGoogleApiClient() { + mGoogleApiClient = new GoogleApiClient.Builder(this) + .addConnectionCallbacks(this) + .addOnConnectionFailedListener(this) + .addApi(LocationServices.API) + .build(); + mGoogleApiClient.connect(); + } + + private boolean checkPlayServices() { + int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); + if (resultCode != ConnectionResult.SUCCESS) + { + if(GooglePlayServicesUtil.isUserRecoverableError(resultCode)) + GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICE_RES_REQUEST).show(); + else { + Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show(); + finish(); + } + return false; + } + return true; + } + + + @Override + public void onMapReady(GoogleMap googleMap) { + try { + boolean isSuccess = googleMap.setMapStyle( + MapStyleOptions.loadRawResourceStyle(this, R.raw.uber_style_map) + ); + if (!isSuccess) + Log.e("ERROR","Map style load failed !!!"); + } + catch (Resources.NotFoundException ex) + { + ex.printStackTrace(); + } + mMap = googleMap; + + riderMarker = mMap.addCircle(new CircleOptions() + .center(new LatLng(riderLat,riderLng)) + .radius(50) //50=> radius is 50m + .strokeColor(Color.BLUE) + .fillColor(0x220000FF) + .strokeWidth(5.0f)); + + //Create Goe fencing with raduis is 50m + geoFire=new GeoFire(FirebaseDatabase.getInstance().getReference(Common.driver_tb1)); + GeoQuery geoQuery = geoFire.queryAtLocation(new GeoLocation(riderLat,riderLng), 0.05f); + geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() { + @Override + public void onKeyEntered(String key, GeoLocation location) { + //Because here we will need customer Id (rider id) to send notification + //so, we will pass it from previous activity (customercall) + sendArrivedNotification(customerId); + btnStartTrip.setEnabled(true); + + } + + @Override + public void onKeyExited(String key) { + + } + + @Override + public void onKeyMoved(String key, GeoLocation location) { + + } + + @Override + public void onGeoQueryReady() { + + } + + @Override + public void onGeoQueryError(DatabaseError error) { + + } + }); + + + + + } + + private void sendArrivedNotification(String customerId) { + Token token = new Token(customerId); + Notification notification = new Notification("Arrived",String.format("The driver %s has arrived at your location",Common.currentUser.getName())); + Sender sender = new Sender(token.getToken(),notification); + + mFCMService.sendMessage(sender).enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + if (response.body().success!=1) + { + Toast.makeText(DriverTracking.this, "Failed", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + } + + private void sendDropOffNotification(String customerId) { + Token token = new Token(customerId); + Notification notification = new Notification("DropOff",customerId); + Sender sender = new Sender(token.getToken(),notification); + + mFCMService.sendMessage(sender).enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + if (response.body().success!=1) + { + Toast.makeText(DriverTracking.this, "Failed", Toast.LENGTH_SHORT).show(); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + + } + }); + } + + + private void displayLocation() { + if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) + { + return; + } + Common.mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); + if(Common.mLastLocation != null) + { + + final double latitude = Common.mLastLocation.getLatitude(); + final double longitude = Common.mLastLocation.getLongitude(); + + if (driverMarker !=null) + driverMarker.remove(); + driverMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(latitude,longitude)) + .title("You") + .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); + + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),17.0f)); + + if (direction!=null) + direction.remove(); //remove old direction + getDirection(); + + + + + + } + else + { + Log.d("Error","Cannot get your location"); + } + } + + private void getDirection() { + LatLng currentPosition = new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude()); + + String requestApi = null; + try { + requestApi = "https://maps.googleapis.com/maps/api/directions/json?"+ + "mode=driving&"+ + "transit_routing_preference=less_driving&"+ + "origin="+currentPosition.latitude+","+currentPosition.longitude+"&"+ + "destination="+riderLat+","+riderLng+"&"+ + "key="+getResources().getString(R.string.google_direction_api); + Log.d("UBER",requestApi); //Print URL for debug + mService.getPath(requestApi) + .enqueue(new Callback() { + @Override + public void onResponse(Call call, Response response) { + + try { + + new ParserTask().execute(response.body().toString()); + + } catch (Exception e) { + e.printStackTrace(); + } + + } + + @Override + public void onFailure(Call call, Throwable t) { + Toast.makeText(DriverTracking.this, ""+t.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + + }catch (Exception e) + { + e.printStackTrace(); + } + + } + + private void startLocationUpdates() { + if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED && + ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) + { + return; + } + LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,this); + } + + @Override + public void onConnected(@Nullable Bundle bundle) { + displayLocation(); + startLocationUpdates(); + } + + @Override + public void onConnectionSuspended(int i) { + mGoogleApiClient.connect(); + } + + @Override + public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { + + } + + @Override + public void onLocationChanged(Location location) { + + Common.mLastLocation = location; + displayLocation(); + + } + + private class ParserTask extends AsyncTask>>> + { + ProgressDialog mDialog = new ProgressDialog(DriverTracking.this); + + @Override + protected void onPreExecute() { + super.onPreExecute(); + mDialog.setMessage("Please wait..."); + mDialog.show(); + } + + @Override + protected List>> doInBackground(String... strings) { + JSONObject jObject; + List>> routes = null; + try { + jObject = new JSONObject(strings[0]); + DirectionJSONParser parser = new DirectionJSONParser(); + routes = parser.parse(jObject); + } catch (JSONException e) { + e.printStackTrace(); + } + return routes; + } + + @Override + protected void onPostExecute(List>> lists) { + mDialog.dismiss(); + + ArrayList points=null; + PolylineOptions polylineOptions = null; + + for (int i=0;i> path = lists.get(i); + + for (int j=0;j point = path.get(j); + + double lat=Double.parseDouble(point.get("lat")); + + double lng=Double.parseDouble(point.get("lng")); + LatLng positon = new LatLng(lat,lng); + + points.add(positon); + } + + polylineOptions.addAll(points); + polylineOptions.width(10); + polylineOptions.color(Color.RED); + polylineOptions.geodesic(true); + } + + direction = mMap.addPolyline(polylineOptions); + + } + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Helper/DirectionJSONParser.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Helper/DirectionJSONParser.java new file mode 100644 index 0000000..07ebb0e --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Helper/DirectionJSONParser.java @@ -0,0 +1,98 @@ +package com.softup.utkarsh.uber.Helper; + +import com.google.android.gms.maps.model.LatLng; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class DirectionJSONParser { + /** Receives a JSONObject and returns a list of lists containing latitude and longitude */ + public List>> parse(JSONObject jObject){ + + List>> routes = new ArrayList>>(); + JSONArray jRoutes = null; + JSONArray jLegs = null; + JSONArray jSteps = null; + + try { + + jRoutes = jObject.getJSONArray("routes"); + + /** Traversing all routes */ + for(int i=0;i>(); + + /** Traversing all legs */ + for(int j=0;j hm = new HashMap(); + hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) ); + hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) ); + path.add(hm); + } + } + routes.add(path); + } + } + + } catch (JSONException e) { + e.printStackTrace(); + }catch (Exception e){ + } + + return routes; + } + + /** + * Method to decode polyline points + * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java + * */ + private List decodePoly(String encoded) { + + List poly = new ArrayList(); + int index = 0, len = encoded.length(); + int lat = 0, lng = 0; + + while (index < len) { + int b, shift = 0, result = 0; + do { + b = encoded.charAt(index++) - 63; + result |= (b & 0x1f) << shift; + shift += 5; + } while (b >= 0x20); + int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); + lat += dlat; + + shift = 0; + result = 0; + do { + b = encoded.charAt(index++) - 63; + result |= (b & 0x1f) << shift; + shift += 5; + } while (b >= 0x20); + int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); + lng += dlng; + + LatLng p = new LatLng((((double) lat / 1E5)), + (((double) lng / 1E5))); + poly.add(p); + } + + return poly; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/MainActivity.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/MainActivity.java new file mode 100644 index 0000000..cc95aff --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/MainActivity.java @@ -0,0 +1,355 @@ +package com.softup.utkarsh.uber; + +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.support.annotation.NonNull; +import android.support.design.widget.Snackbar; +import android.support.v7.app.AlertDialog; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.MotionEvent; +import android.view.View; +import android.widget.Button; +import android.widget.RelativeLayout; +import android.widget.TextView; + +import com.google.android.gms.tasks.OnCompleteListener; +import com.google.android.gms.tasks.OnFailureListener; +import com.google.android.gms.tasks.OnSuccessListener; +import com.google.android.gms.tasks.Task; +import com.google.firebase.auth.AuthResult; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.ValueEventListener; +import com.rengwuxian.materialedittext.MaterialEditText; +import com.softup.utkarsh.uber.Common.Common; +import com.softup.utkarsh.uber.Model.User; + +import dmax.dialog.SpotsDialog; +import uk.co.chrisjenx.calligraphy.CalligraphyConfig; +import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; + +public class MainActivity extends AppCompatActivity{ + + Button btnSignIn,btnRegister; + RelativeLayout rootLayout; + FirebaseAuth auth; + FirebaseDatabase db; + DatabaseReference users; + TextView txt_forgot_pwd; + + @Override + protected void attachBaseContext(Context newBase) { + super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); + } + + @Override + protected void onCreate(Bundle savedInstanceState) + { + super.onCreate(savedInstanceState); + //Before setContentView + CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() + .setDefaultFontPath("fonts/Arkhip_font.ttf") + .setFontAttrId(R.attr.fontPath) + .build()); + setContentView(R.layout.activity_main); + + //Init FireBase + auth = FirebaseAuth.getInstance(); + db= FirebaseDatabase.getInstance(); + users= db.getReference(Common.user_driver_tb1); + + + + //Init View + btnRegister = (Button)findViewById(R.id.btnRegister); + btnSignIn = (Button)findViewById(R.id.btnSignIn); + rootLayout = (RelativeLayout)findViewById(R.id.rootLayout); + txt_forgot_pwd = (TextView)findViewById(R.id.txt_forgot_password); + txt_forgot_pwd.setOnTouchListener(new View.OnTouchListener() { + @Override + public boolean onTouch(View view, MotionEvent motionEvent) { + showDialogForgotPwd(); + return false; + } + }); + + //Event + btnRegister.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + showRegisterDialog(); + } + }); + + btnSignIn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + showLoginDialog(); + } + }); + + } + + private void showDialogForgotPwd() { + AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); + alertDialog.setTitle("FORGOT PASSWORD"); + alertDialog.setMessage("Please enter your email address"); + + LayoutInflater inflater = LayoutInflater.from(MainActivity.this); + View forgot_pwd_layout = inflater.inflate(R.layout.layout_forgot_pwd,null); + final MaterialEditText edtEmail = (MaterialEditText)forgot_pwd_layout.findViewById(R.id.edtEmail); + alertDialog.setView(forgot_pwd_layout); + + //Set Button + alertDialog.setPositiveButton("RESET", new DialogInterface.OnClickListener() { + @Override + public void onClick(final DialogInterface dialogInterface, int i) { + final SpotsDialog waitingDialog = new SpotsDialog(MainActivity.this); + waitingDialog.show(); + + auth.sendPasswordResetEmail(edtEmail.getText().toString().trim()) + .addOnCompleteListener(new OnCompleteListener() { + @Override + public void onComplete(@NonNull Task task) { + dialogInterface.dismiss(); + waitingDialog.dismiss(); + + Snackbar.make(rootLayout,"Reset password link has been sent",Snackbar.LENGTH_LONG) + .show(); + + } + }).addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + dialogInterface.dismiss(); + waitingDialog.dismiss(); + + Snackbar.make(rootLayout,""+e.getMessage(),Snackbar.LENGTH_LONG) + .show(); + + + } + }); + } + }); + + alertDialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + alertDialog.show(); + } + + private void showLoginDialog() { + final AlertDialog.Builder dialog = new AlertDialog.Builder(this); + dialog.setTitle("SIGN IN"); + dialog.setMessage("Please use email to sign in"); + + LayoutInflater inflater = LayoutInflater.from(this); + View login_layout = inflater.inflate(R.layout.layout_login,null); + + final MaterialEditText edtEmail = login_layout.findViewById(R.id.edtEmail); + final MaterialEditText edtPassword = login_layout.findViewById(R.id.edtPassword); + + + dialog.setView(login_layout); + + //Set button + + dialog.setPositiveButton("SIGN IN", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + + dialogInterface.dismiss(); + + //Set disable button Sign In if is processing + btnSignIn.setEnabled(false); + + + //Check validation + if (TextUtils.isEmpty(edtEmail.getText().toString())) { + Snackbar.make(rootLayout, "Please enter email address", Snackbar.LENGTH_SHORT).show(); + return; + } + + + if (edtPassword.getText().toString().length() < 6) { + Snackbar.make(rootLayout, "Password must be greater than 6 letter!!!", Snackbar.LENGTH_SHORT).show(); + return; + } + + final SpotsDialog waitingDialog = new SpotsDialog(MainActivity.this); + waitingDialog.show(); + + + //Login + auth.signInWithEmailAndPassword(edtEmail.getText().toString(),edtPassword.getText().toString()) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(AuthResult authResult) { + waitingDialog.dismiss(); + FirebaseDatabase.getInstance().getReference(Common.user_driver_tb1) + .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .addListenerForSingleValueEvent(new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + Common.currentUser = dataSnapshot.getValue(User.class); + startActivity(new Intent(MainActivity.this,DriverHome.class)); + finish(); + } + + @Override + public void onCancelled(DatabaseError databaseError) { + + } + }); + + + + + + + } + }).addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + waitingDialog.dismiss(); + Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT).show(); + + //Active button + btnSignIn.setEnabled(true); + } + }); + + + } + }); + + dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + + + + + + + + + dialog.show(); + + } + + private void showRegisterDialog() + { + final AlertDialog.Builder dialog = new AlertDialog.Builder(this); + dialog.setTitle("REGISTER"); + dialog.setMessage("Please use email to register"); + + LayoutInflater inflater = LayoutInflater.from(this); + View register_layout = inflater.inflate(R.layout.layout_register,null); + + final MaterialEditText edtEmail = register_layout.findViewById(R.id.edtEmail); + final MaterialEditText edtPassword = register_layout.findViewById(R.id.edtPassword); + final MaterialEditText edtName = register_layout.findViewById(R.id.edtName); + final MaterialEditText edtPhone = register_layout.findViewById(R.id.edtPhone); + + dialog.setView(register_layout); + + //Set button + + dialog.setPositiveButton("REGISTER", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + + dialogInterface.dismiss(); + + //Check validation + if (TextUtils.isEmpty(edtEmail.getText().toString())) + { + Snackbar.make(rootLayout,"Please enter email address",Snackbar.LENGTH_SHORT).show(); + return; + } + + if (TextUtils.isEmpty(edtPhone.getText().toString())) + { + Snackbar.make(rootLayout,"Please enter phone number",Snackbar.LENGTH_SHORT).show(); + return; + } + + if (edtPassword.getText().toString().length() < 6) + { + Snackbar.make(rootLayout,"Password must be greater than 6 letter!!!",Snackbar.LENGTH_SHORT).show(); + return; + } + + //Register new user + auth.createUserWithEmailAndPassword(edtEmail.getText().toString(),edtPassword.getText().toString()) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(AuthResult authResult) { + //Save user to db + User user = new User(); + user.setEmail(edtEmail.getText().toString()); + user.setName(edtName.getText().toString()); + user.setPhone(edtPhone.getText().toString()); + user.setPassword(edtPassword.getText().toString()); + user.setAvatarUrl("https://firebasestorage.googleapis.com/v0/b/uber-798e0.appspot.com/o/add_image.png?alt=media&token=4433425f-b9dd-47f1-9364-a70679cefb7a"); + user.setRates("0.0"); + + //Use email to key + users.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .setValue(user) + .addOnSuccessListener(new OnSuccessListener() { + @Override + public void onSuccess(Void aVoid) { + Snackbar.make(rootLayout,"Register success fully!!!",Snackbar.LENGTH_SHORT).show(); + + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT).show(); + + } + }); + + } + }) + .addOnFailureListener(new OnFailureListener() { + @Override + public void onFailure(@NonNull Exception e) { + Snackbar.make(rootLayout,"Failed"+e.getMessage(),Snackbar.LENGTH_SHORT).show(); + } + }); + + + + + } + }); + + dialog.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + dialogInterface.dismiss(); + } + }); + + dialog.show(); + + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/FCMResponse.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/FCMResponse.java new file mode 100644 index 0000000..a39ff33 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/FCMResponse.java @@ -0,0 +1,64 @@ +package com.softup.utkarsh.uber.Model; + +import java.util.List; + +public class FCMResponse { + + public long multicast_id; + public int success; + public int failure; + public int canonical_ids; + public List results; + + public FCMResponse() { + } + + public FCMResponse(long multicast_id, int success, int failure, int canonical_ids, List results) { + + this.multicast_id = multicast_id; + this.success = success; + this.failure = failure; + this.canonical_ids = canonical_ids; + this.results = results; + } + + public long getMulticast_id() { + return multicast_id; + } + + public void setMulticast_id(long multicast_id) { + this.multicast_id = multicast_id; + } + + public int getSuccess() { + return success; + } + + public void setSuccess(int success) { + this.success = success; + } + + public int getFailure() { + return failure; + } + + public void setFailure(int failure) { + this.failure = failure; + } + + public int getCanonical_ids() { + return canonical_ids; + } + + public void setCanonical_ids(int canonical_ids) { + this.canonical_ids = canonical_ids; + } + + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Notification.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Notification.java new file mode 100644 index 0000000..bf96688 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Notification.java @@ -0,0 +1,11 @@ +package com.softup.utkarsh.uber.Model; + +public class Notification { + public String title; + public String body; + + public Notification(String title, String body) { + this.title = title; + this.body = body; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Result.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Result.java new file mode 100644 index 0000000..b79a767 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Result.java @@ -0,0 +1,20 @@ +package com.softup.utkarsh.uber.Model; + +public class Result { + public String message_id; + + public Result() { + } + + public Result(String message_id) { + this.message_id = message_id; + } + + public String getMessage_id() { + return message_id; + } + + public void setMessage_id(String message_id) { + this.message_id = message_id; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Sender.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Sender.java new file mode 100644 index 0000000..be888f2 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Sender.java @@ -0,0 +1,30 @@ +package com.softup.utkarsh.uber.Model; + +public class Sender { + public String to; + public Notification notification; + + public Sender(String to, Notification notification) { + this.to = to; + this.notification = notification; + } + + public Sender() { + } + + public String getTo() { + return to; + } + + public void setTo(String to) { + this.to = to; + } + + public Notification getNotification() { + return notification; + } + + public void setNotification(Notification notification) { + this.notification = notification; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Token.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Token.java new file mode 100644 index 0000000..05510da --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/Token.java @@ -0,0 +1,20 @@ +package com.softup.utkarsh.uber.Model; + +public class Token { + private String token; + + public Token() { + } + + public Token(String token) { + this.token = token; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/User.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/User.java new file mode 100644 index 0000000..fda2750 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Model/User.java @@ -0,0 +1,68 @@ +package com.softup.utkarsh.uber.Model; + +public class User { + private String email,password,name,phone,avatarUrl,rates; + + public User() { + + } + + public User(String email, String password, String name, String phone,String avatarUrl,String rates) { + this.email = email; + this.password = password; + this.name = name; + this.phone = phone; + this.avatarUrl = avatarUrl; + this.rates = rates; + + + } + + public String getRates() { + return rates; + } + + public void setRates(String rates) { + this.rates = rates; + } + + public String getAvatarUrl() { + return avatarUrl; + } + + public void setAvatarUrl(String avatarUrl) { + this.avatarUrl = avatarUrl; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/FCMClient.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/FCMClient.java new file mode 100644 index 0000000..3945d06 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/FCMClient.java @@ -0,0 +1,21 @@ +package com.softup.utkarsh.uber.Remote; + +import retrofit2.Retrofit; +import retrofit2.converter.gson.GsonConverterFactory; +import retrofit2.converter.scalars.ScalarsConverterFactory; + +public class FCMClient { + private static Retrofit retrofit =null; + + public static Retrofit getClient(String baseURL) + { + if(retrofit == null) + { + retrofit = new Retrofit.Builder() + .baseUrl(baseURL) + .addConverterFactory(GsonConverterFactory.create()) + .build(); + } + return retrofit; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/IFCMService.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/IFCMService.java new file mode 100644 index 0000000..0c4eaee --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/IFCMService.java @@ -0,0 +1,18 @@ +package com.softup.utkarsh.uber.Remote; + +import com.softup.utkarsh.uber.Model.FCMResponse; +import com.softup.utkarsh.uber.Model.Sender; + +import retrofit2.Call; +import retrofit2.http.Body; +import retrofit2.http.Headers; +import retrofit2.http.POST; + +public interface IFCMService { + @Headers({ + "Content-Type:application/json", + "Authorization:key=AAAABQj5y1g:APA91bHgHSVtQPQPXfeLVgjQZ9XiTPPykaiTn1BqICyCznRa5H8ZKrQsYMdQIUa1F_VQQDR4iYLPdcM7BPNWm5DsktAAEoo0FobgcLFVeizQxh-x9VcQ04xMI-bziJJ8CI0BUQMg9oX1" + }) + @POST("fcm/send") + Call sendMessage(@Body Sender body); +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/IGoogleAPI.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/IGoogleAPI.java new file mode 100644 index 0000000..9582291 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/IGoogleAPI.java @@ -0,0 +1,10 @@ +package com.softup.utkarsh.uber.Remote; + +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.Url; + +public interface IGoogleAPI { + @GET + Call getPath(@Url String url); +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/RetrofitClient.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/RetrofitClient.java new file mode 100644 index 0000000..f6f5e57 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Remote/RetrofitClient.java @@ -0,0 +1,20 @@ +package com.softup.utkarsh.uber.Remote; + +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; + +public class RetrofitClient { + private static Retrofit retrofit =null; + + public static Retrofit getClient(String baseURL) + { + if(retrofit == null) + { + retrofit = new Retrofit.Builder() + .baseUrl(baseURL) + .addConverterFactory(ScalarsConverterFactory.create()) + .build(); + } + return retrofit; + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Service/MyFirebaseIdService.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Service/MyFirebaseIdService.java new file mode 100644 index 0000000..ac082b6 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Service/MyFirebaseIdService.java @@ -0,0 +1,30 @@ +package com.softup.utkarsh.uber.Service; + +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.iid.FirebaseInstanceId; +import com.google.firebase.iid.FirebaseInstanceIdService; +import com.softup.utkarsh.uber.Common.Common; +import com.softup.utkarsh.uber.Model.Token; + +public class MyFirebaseIdService extends FirebaseInstanceIdService { + + @Override + public void onTokenRefresh() { + super.onTokenRefresh(); + String refreshedToken = FirebaseInstanceId.getInstance().getToken(); + updateTokenToServer(refreshedToken); //When have refreshed token, we need to update to our Realtime database + + } + + private void updateTokenToServer(String refreshedToken) { + FirebaseDatabase db = FirebaseDatabase.getInstance(); + DatabaseReference tokens = db.getReference(Common.token_tb1); + + Token token = new Token(refreshedToken); + if (FirebaseAuth.getInstance().getCurrentUser() != null) //if already login , must update Token + tokens.child(FirebaseAuth.getInstance().getCurrentUser().getUid()) + .setValue(token); + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/Service/MyFirebaseMessaging.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Service/MyFirebaseMessaging.java new file mode 100644 index 0000000..6e43954 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/Service/MyFirebaseMessaging.java @@ -0,0 +1,27 @@ +package com.softup.utkarsh.uber.Service; + +import android.content.Intent; + +import com.google.android.gms.maps.model.LatLng; +import com.google.firebase.messaging.FirebaseMessagingService; +import com.google.firebase.messaging.RemoteMessage; +import com.google.gson.Gson; +import com.softup.utkarsh.uber.CustommerCall; + +public class MyFirebaseMessaging extends FirebaseMessagingService { + + @Override + public void onMessageReceived(RemoteMessage remoteMessage) { + + LatLng customer_location = new Gson().fromJson(remoteMessage.getNotification().getBody(),LatLng.class); + + Intent intent = new Intent(getBaseContext(), CustommerCall.class); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + intent.putExtra("lat",customer_location.latitude); + intent.putExtra("lng",customer_location.longitude); + intent.putExtra("customer",remoteMessage.getNotification().getTitle()); + + startActivity(intent); + + } +} diff --git a/Complete code/app/src/main/java/com/softup/utkarsh/uber/TripDetail.java b/Complete code/app/src/main/java/com/softup/utkarsh/uber/TripDetail.java new file mode 100644 index 0000000..ccc3ae3 --- /dev/null +++ b/Complete code/app/src/main/java/com/softup/utkarsh/uber/TripDetail.java @@ -0,0 +1,120 @@ +package com.softup.utkarsh.uber; + +import android.content.Intent; +import android.support.v4.app.FragmentActivity; +import android.os.Bundle; +import android.widget.TextView; + +import com.google.android.gms.maps.CameraUpdateFactory; +import com.google.android.gms.maps.GoogleMap; +import com.google.android.gms.maps.OnMapReadyCallback; +import com.google.android.gms.maps.SupportMapFragment; +import com.google.android.gms.maps.model.BitmapDescriptorFactory; +import com.google.android.gms.maps.model.LatLng; +import com.google.android.gms.maps.model.MarkerOptions; +import com.google.firebase.auth.FirebaseAuth; +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.ValueEventListener; +import com.softup.utkarsh.uber.Common.Common; +import com.softup.utkarsh.uber.Model.User; + +import java.util.Calendar; + +public class TripDetail extends FragmentActivity implements OnMapReadyCallback { + + private GoogleMap mMap; + + private TextView txtDate,txtFee,txtBaseFare,txtTime,txtDistance,txtEstimatedPayout,txtFrom,txtTo; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_trip_detail); + // Obtain the SupportMapFragment and get notified when the map is ready to be used. + SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() + .findFragmentById(R.id.map); + mapFragment.getMapAsync(this); + + //InitView + txtBaseFare = (TextView)findViewById(R.id.txtBaseFare); + txtDate = (TextView)findViewById(R.id.txtDate); + txtFee = (TextView)findViewById(R.id.txtFee); + txtTime = (TextView)findViewById(R.id.txtTime); + txtDistance = (TextView)findViewById(R.id.txtDistance); + txtEstimatedPayout = (TextView)findViewById(R.id.txtEstimatedPayout); + txtFrom = (TextView)findViewById(R.id.txtFrom); + txtTo = (TextView)findViewById(R.id.txtTo); + } + + + /** + * Manipulates the map once available. + * This callback is triggered when the map is ready to be used. + * This is where we can add markers or lines, add listeners or move the camera. In this case, + * we just add a marker near Sydney, Australia. + * If Google Play services is not installed on the device, the user will be prompted to install + * it inside the SupportMapFragment. This method will only be triggered once the user has + * installed Google Play services and returned to the app. + */ + @Override + public void onMapReady(GoogleMap googleMap) { + mMap = googleMap; + + settingInformation(); + + } + + private void settingInformation() { + if(getIntent() != null) + { + //Set Text + Calendar calendar = Calendar.getInstance(); + String date = String.format("%s, %d/%d",convertToDayOfWeek(calendar.get(Calendar.DAY_OF_WEEK)),calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH)+1); + txtDate.setText(date); + txtFee.setText(String.format("$ %.2f",getIntent().getDoubleExtra("total",0.0))); + txtEstimatedPayout.setText(String.format("$ %.2f",getIntent().getDoubleExtra("total",0.0))); + txtBaseFare.setText(String.format("$ %.2f", Common.base_fare)); + txtTime.setText(String.format("%s min",getIntent().getStringExtra("time"))); + txtDistance.setText(String.format("%s km",getIntent().getStringExtra("distance"))); + txtFrom.setText(getIntent().getStringExtra("start_address")); + txtTo.setText(getIntent().getStringExtra("end_address")); + + //Add Marker + String[] location_end = getIntent().getStringExtra("location_end").split(","); + LatLng dropoff = new LatLng (Double.parseDouble(location_end[0]),Double.parseDouble(location_end[1])); + mMap.addMarker(new MarkerOptions().position(dropoff) + .title("Drop off Here") + .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))); + + mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(dropoff,12.0f)); + + } + } + + private String convertToDayOfWeek(int day) { + switch (day) + { + case Calendar.SUNDAY: + return "SUNDAY"; + case Calendar.MONDAY: + return "MONDAY"; + case Calendar.TUESDAY: + return "TUESDAY"; + case Calendar.WEDNESDAY: + return "WEDNESDAY"; + case Calendar.THURSDAY: + return "THURSDAY"; + case Calendar.FRIDAY: + return "FRIDAY"; + case Calendar.SATURDAY: + return "SATURDAY"; + default: + return "UNK"; + } + } + + +} diff --git a/Complete code/app/src/main/res/drawable-hdpi/ic_location_off.png b/Complete code/app/src/main/res/drawable-hdpi/ic_location_off.png new file mode 100644 index 0000000..de70312 Binary files /dev/null and b/Complete code/app/src/main/res/drawable-hdpi/ic_location_off.png differ diff --git a/Complete code/app/src/main/res/drawable-hdpi/ic_location_on.png b/Complete code/app/src/main/res/drawable-hdpi/ic_location_on.png new file mode 100644 index 0000000..ef1becc Binary files /dev/null and b/Complete code/app/src/main/res/drawable-hdpi/ic_location_on.png differ diff --git a/Complete code/app/src/main/res/drawable-mdpi/destination_marker.png b/Complete code/app/src/main/res/drawable-mdpi/destination_marker.png new file mode 100644 index 0000000..dac28fd Binary files /dev/null and b/Complete code/app/src/main/res/drawable-mdpi/destination_marker.png differ diff --git a/Complete code/app/src/main/res/drawable-mdpi/ic_location_off.png b/Complete code/app/src/main/res/drawable-mdpi/ic_location_off.png new file mode 100644 index 0000000..24168a8 Binary files /dev/null and b/Complete code/app/src/main/res/drawable-mdpi/ic_location_off.png differ diff --git a/Complete code/app/src/main/res/drawable-mdpi/ic_location_on.png b/Complete code/app/src/main/res/drawable-mdpi/ic_location_on.png new file mode 100644 index 0000000..346cfa7 Binary files /dev/null and b/Complete code/app/src/main/res/drawable-mdpi/ic_location_on.png differ diff --git a/Complete code/app/src/main/res/drawable-mdpi/marker.png b/Complete code/app/src/main/res/drawable-mdpi/marker.png new file mode 100644 index 0000000..51fa7b6 Binary files /dev/null and b/Complete code/app/src/main/res/drawable-mdpi/marker.png differ diff --git a/Complete code/app/src/main/res/drawable-v21/ic_menu_camera.xml b/Complete code/app/src/main/res/drawable-v21/ic_menu_camera.xml new file mode 100644 index 0000000..0d9ea10 --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v21/ic_menu_camera.xml @@ -0,0 +1,12 @@ + + + + diff --git a/Complete code/app/src/main/res/drawable-v21/ic_menu_gallery.xml b/Complete code/app/src/main/res/drawable-v21/ic_menu_gallery.xml new file mode 100644 index 0000000..f6872c4 --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v21/ic_menu_gallery.xml @@ -0,0 +1,9 @@ + + + diff --git a/Complete code/app/src/main/res/drawable-v21/ic_menu_manage.xml b/Complete code/app/src/main/res/drawable-v21/ic_menu_manage.xml new file mode 100644 index 0000000..c1be60b --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v21/ic_menu_manage.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/Complete code/app/src/main/res/drawable-v21/ic_menu_send.xml b/Complete code/app/src/main/res/drawable-v21/ic_menu_send.xml new file mode 100644 index 0000000..00c668c --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v21/ic_menu_send.xml @@ -0,0 +1,9 @@ + + + diff --git a/Complete code/app/src/main/res/drawable-v21/ic_menu_share.xml b/Complete code/app/src/main/res/drawable-v21/ic_menu_share.xml new file mode 100644 index 0000000..a28fb9e --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v21/ic_menu_share.xml @@ -0,0 +1,9 @@ + + + diff --git a/Complete code/app/src/main/res/drawable-v21/ic_menu_slideshow.xml b/Complete code/app/src/main/res/drawable-v21/ic_menu_slideshow.xml new file mode 100644 index 0000000..209aa64 --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v21/ic_menu_slideshow.xml @@ -0,0 +1,9 @@ + + + diff --git a/Complete code/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/Complete code/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/Complete code/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/Complete code/app/src/main/res/drawable-xhdpi/ic_location_off.png b/Complete code/app/src/main/res/drawable-xhdpi/ic_location_off.png new file mode 100644 index 0000000..77857f1 Binary files /dev/null and b/Complete code/app/src/main/res/drawable-xhdpi/ic_location_off.png differ diff --git a/Complete code/app/src/main/res/drawable-xhdpi/ic_location_on.png b/Complete code/app/src/main/res/drawable-xhdpi/ic_location_on.png new file mode 100644 index 0000000..695173f Binary files /dev/null and b/Complete code/app/src/main/res/drawable-xhdpi/ic_location_on.png differ diff --git a/Complete code/app/src/main/res/drawable-xxhdpi/ic_location_off.png b/Complete code/app/src/main/res/drawable-xxhdpi/ic_location_off.png new file mode 100644 index 0000000..955762a Binary files /dev/null and b/Complete code/app/src/main/res/drawable-xxhdpi/ic_location_off.png differ diff --git a/Complete code/app/src/main/res/drawable-xxhdpi/ic_location_on.png b/Complete code/app/src/main/res/drawable-xxhdpi/ic_location_on.png new file mode 100644 index 0000000..34b56d3 Binary files /dev/null and b/Complete code/app/src/main/res/drawable-xxhdpi/ic_location_on.png differ diff --git a/Complete code/app/src/main/res/drawable/add_image.png b/Complete code/app/src/main/res/drawable/add_image.png new file mode 100644 index 0000000..bda4367 Binary files /dev/null and b/Complete code/app/src/main/res/drawable/add_image.png differ diff --git a/Complete code/app/src/main/res/drawable/background.jpg b/Complete code/app/src/main/res/drawable/background.jpg new file mode 100644 index 0000000..8f6d0de Binary files /dev/null and b/Complete code/app/src/main/res/drawable/background.jpg differ diff --git a/Complete code/app/src/main/res/drawable/btn_register_background.xml b/Complete code/app/src/main/res/drawable/btn_register_background.xml new file mode 100644 index 0000000..507dc7f --- /dev/null +++ b/Complete code/app/src/main/res/drawable/btn_register_background.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/Complete code/app/src/main/res/drawable/btn_sign_in_background.xml b/Complete code/app/src/main/res/drawable/btn_sign_in_background.xml new file mode 100644 index 0000000..e4c8fd3 --- /dev/null +++ b/Complete code/app/src/main/res/drawable/btn_sign_in_background.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/Complete code/app/src/main/res/drawable/camera.png b/Complete code/app/src/main/res/drawable/camera.png new file mode 100644 index 0000000..4800497 Binary files /dev/null and b/Complete code/app/src/main/res/drawable/camera.png differ diff --git a/Complete code/app/src/main/res/drawable/car.png b/Complete code/app/src/main/res/drawable/car.png new file mode 100644 index 0000000..96d711d Binary files /dev/null and b/Complete code/app/src/main/res/drawable/car.png differ diff --git a/Complete code/app/src/main/res/drawable/ic_launcher_background.xml b/Complete code/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..d5fccc5 --- /dev/null +++ b/Complete code/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Complete code/app/src/main/res/drawable/ic_pin_drop_black_24dp.xml b/Complete code/app/src/main/res/drawable/ic_pin_drop_black_24dp.xml new file mode 100644 index 0000000..49a3317 --- /dev/null +++ b/Complete code/app/src/main/res/drawable/ic_pin_drop_black_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/Complete code/app/src/main/res/drawable/ic_star_white_24dp.xml b/Complete code/app/src/main/res/drawable/ic_star_white_24dp.xml new file mode 100644 index 0000000..fa1c999 --- /dev/null +++ b/Complete code/app/src/main/res/drawable/ic_star_white_24dp.xml @@ -0,0 +1,9 @@ + + + diff --git a/Complete code/app/src/main/res/drawable/map.PNG b/Complete code/app/src/main/res/drawable/map.PNG new file mode 100644 index 0000000..fac3417 Binary files /dev/null and b/Complete code/app/src/main/res/drawable/map.PNG differ diff --git a/Complete code/app/src/main/res/drawable/side_nav_bar.xml b/Complete code/app/src/main/res/drawable/side_nav_bar.xml new file mode 100644 index 0000000..6d81870 --- /dev/null +++ b/Complete code/app/src/main/res/drawable/side_nav_bar.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/Complete code/app/src/main/res/layout/activity_custommer_call.xml b/Complete code/app/src/main/res/layout/activity_custommer_call.xml new file mode 100644 index 0000000..516eed4 --- /dev/null +++ b/Complete code/app/src/main/res/layout/activity_custommer_call.xml @@ -0,0 +1,85 @@ + + + + + + + + + + + + + + + + + +