unable to get current location using FusedLocationApi without Gps - android

I am trying to get users current location using FusedLocationApi using the following code. I am following the guide provided here: https://developer.android.com/training/location/retrieve-current.html
I have tried this so far:
package com.abhishek.locationawareapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
protected void createLocationRequest(){
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Main Activity: ","onCreate");
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();//.addApi(LocationServices.class)
}
//For Location Request
/*LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);*/
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
Log.d("Main Activity: ","onStart");
super.onStart();
}
#Override
protected void onStop() {
Log.d("Main Activity: ","onStop");
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.d("Main Activity: ","onConnected");
if(Build.VERSION.SDK_INT >=23){
checkLocationPermission();
}else{
locationPermission = true;
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation !=null){
String mLatitudeText = String.valueOf(mLastLocation.getLatitude());
String mLongitudeText = String.valueOf(mLastLocation.getLongitude());
Log.d("Location: ","mLatitudeText: "+ mLatitudeText +" mLongitudeText: "+ mLongitudeText);
}
}
}
boolean locationPermission = false;
final static int LOC_REQ_CODE = 100;
private void checkLocationPermission(){
int locationPermissionCheck = ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION);
if(locationPermissionCheck == PackageManager.PERMISSION_GRANTED){
locationPermission = true;
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation !=null){
String mLatitudeText = String.valueOf(mLastLocation.getLatitude());
String mLongitudeText = String.valueOf(mLastLocation.getLongitude());
Log.d("Location: ","mLatitudeText: "+ mLatitudeText +" mLongitudeText: "+ mLongitudeText);
}
}else{
locationPermission = false;
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOC_REQ_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case LOC_REQ_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
locationPermission = true;
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLastLocation !=null){
String mLatitudeText = String.valueOf(mLastLocation.getLatitude());
String mLongitudeText = String.valueOf(mLastLocation.getLongitude());
Log.d("Location: ","mLatitudeText: "+ mLatitudeText +" mLongitudeText: "+ mLongitudeText);
}
}else{
final Snackbar snackBar = Snackbar.make(findViewById(R.id.rl_layout), "Location access is required to get last location.",
Snackbar.LENGTH_INDEFINITE);
snackBar.setAction("Dismiss", new View.OnClickListener() {
#Override
public void onClick(View v) {
checkLocationPermission();
snackBar.dismiss();
}
});
snackBar.show();
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
Log.d("Main Activity: ","onConnectionSuspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d("Main Activity: ","onConnectionFailed");
}
}
I got the location with gps enabled but once i disable gps, mLastLocation
always returns null. Isn't it possible to get location from FusedLocationApi without using Gps? Please help!!

Related

store problem latitude and longitude in realtime Firebase And have the following code

This code is not storing latitude and longitude in firebase realtime database please help me I got stuck in between onlocationchanged method latitude and longitude showing in toast but not storing latitude and longitude in firebase realtime database please help me
firebase Database JAVA
package com.track_location.tracking_system;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.single.PermissionListener;
public class MapsActivity2 extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
DatabaseReference reference;
Button btn;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2000;
private long FASTEST_INTERVAL = 5000;
private LocationManager locationManager;
private LatLng latLng;
private boolean isPermission;
private FirebaseUser user;
private FirebaseAuth auth;
String userid,u1,cust,nm;
DatabaseReference ref;
double latitude;
double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
Intent intent=getIntent();
nm=intent.getStringExtra("userid");
btn=(Button)findViewById(R.id.enable_btn);
auth=FirebaseAuth.getInstance();
user=auth.getCurrentUser();
reference= FirebaseDatabase.getInstance().getReference().child("User");
ref=reference.child(nm);
if(requestSinglePermission()){
// 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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
}
private boolean checkLocation() {
if(!isLocationEnabled()){
showAlert();
}
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean requestSinglePermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
isPermission = true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
// check for permanent denial of permission
if (response.isPermanentlyDenied()) {
isPermission = false;
}
}
#Override
public void onPermissionRationaleShouldBeShown(com.karumi.dexter.listener.PermissionRequest permission, PermissionToken token) {
}
}).check();
return isPermission;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(latLng!=null){
mMap.addMarker(new MarkerOptions().position(latLng).title("Marker in Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14F));
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null) {
startLocationUpdates();
}
else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
private void startLocationUpdates() {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg+nm, Toast.LENGTH_SHORT).show();
latitude=location.getLatitude();
longitude=location.getLongitude();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ref.child("Latitude").push().setValue(latitude);
//Toast.makeText(getApplicationContext(),"Latitude : "+latitude,Toast.LENGTH_LONG).show();
ref.child("Longitude").push().setValue(longitude);
}
});
latLng = new LatLng(location.getLatitude(), location.getLongitude());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onStart() {
super.onStart();
if(mGoogleApiClient !=null){
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if(mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
}
In your current code, the current location is only updated when you click the "enable button".
However, in that code, you are adding a new OnClickListener to that button every time the location is updated. Instead you should define the OnClickListener to publish the current value of latLng (which in the code below I renamed to mLatLng to follow conventions).
// Firebase services
private FirebaseAuth mAuth;
private FirebaseDatabase mDatabase;
// Firebase objects
private FirebaseUser mUser;
private DatabaseReference mUserRef;
// Java objects
private SupportMapFragment mMapFragment;
private LatLng mLatLng;
private String mUserId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps2);
Intent intent = getIntent();
mUserId = intent.getStringExtra("userid");
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser(); // unused?
mDatabase = FirebaseDatabase.getInstance();
mUserRef = mDatabase.child("User").child(mUserId);
if(requestSinglePermission()){
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mMapFragment.getMapAsync(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
final MapsActivity2 self = this;
Button btnEnable = (Button) findViewById(R.id.enable_btn);
btnEnable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// On click, saves last location to Firebase RTDB
long latitude = self.mLatLng.getLatitude();
long longitude = self.mLatLng.getLongitude();
String pushId = mUserRef.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/Latitude/" + pushId, latitude);
childUpdates.put("/Longitude/" + pushId, longitude);
mUserRef.updateChildren(childUpdates)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "btnEnable#onClick:onFailure", databaseError.toException());
}
});
}
});
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg+userId, Toast.LENGTH_SHORT).show();
this.mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
this.mMapFragment.getMapAsync(this);
}
If you wanted to save the current location to the database on every update to the location, you would use:
#Override
public void onLocationChanged(Location location) {
long latitude = location.getLatitude();
long longitude = location.getLongitude();
String msg = "Updated Location: " +
Double.toString(latitude) + "," +
Double.toString(longitude);
Toast.makeText(this, msg+userId, Toast.LENGTH_SHORT).show();
this.mLatLng = new LatLng(latitude, longitude);
String pushId = mUserRef.push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/Latitude/" + pushId, latitude);
childUpdates.put("/Longitude/" + pushId, longitude);
mUserRef.updateChildren(childUpdates)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "onLocationChanged:onFailure", databaseError.toException());
}
});
this.mMapFragment.getMapAsync(this);
}

The String#value field is not present on Android versions >= 6.0

I am creating an app like Uber but I have ran into a problem after I got an error suddenly and the app crashed. I tried out many ways in order to get ride of this error but it didn't work. All the answers to the similar questions that I could find on Stackoverflow were that this problem is caused due to FirebaseDatabase.getInstance().setPersistenceEnabled(true) and I had to delete this code of line as this is a bug with Firebase that is yet to be solved. But this didn't solve my problem as i didn't have any such code. That's why i thought this is a question which is not on stackoverflow and asked the question. This is my Java Code
package com.matt.autozauser;
import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
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.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;
import com.google.android.gms.location.places.ui.PlaceAutocompleteFragment;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
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.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
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.Marker;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Welcome extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
SupportMapFragment mapFragment;
private Button btnBooking;
private Location lastLocation;
private GoogleApiClient.OnConnectionFailedListener onConnectionFailedListener;
private LocationRequest locationRequest;
private LocationListener locationListener;
private LocationManager locationManager;
private Marker marker, driverMarker;
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private final int RequestCode = 10;
private final int ResourceCode = 11;
private DatabaseReference userLastLocation, customersUnderServiceRef, userRequest, driversOnDuty,workingDrivers, driverRef1, driverWorkingRef ;
GeoFire location, onDuty, customersUnderService;
private Boolean clicked = false;
private String driverID = "";
private ValueEventListener driverListener;
private GeoQuery geoQuery;
private String myId = "";
private Double driverLat, driverLng;
private PlaceAutocomplete pickup, drop;
#Override
protected void onCreate(Bundle savedInstanceState)
{
checkLocationPermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
userLastLocation = FirebaseDatabase.getInstance().getReference("User LastLocation");
location = new GeoFire(userLastLocation);
setupLocation();
driversOnDuty = FirebaseDatabase.getInstance().getReference("DriversOnDuty");
onDuty = new GeoFire(driversOnDuty);
driverWorkingRef = FirebaseDatabase.getInstance().getReference().child("DriversWorking");
customersUnderServiceRef = FirebaseDatabase.getInstance().getReference().child("CustomersUnderService");
customersUnderService = new GeoFire(customersUnderServiceRef);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
myId = FirebaseAuth.getInstance().getCurrentUser().getUid();
setupUiViews();
mMap = googleMap;
displayLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
switch (requestCode) {
case RequestCode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()){
buildGoogleApiClient();
createLocationRequest();
displayLocation();
}
}
break;
}
}
#Override
public void onConnected(#Nullable Bundle bundle)
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if (googleApiClient == null){
buildGoogleApiClient();
}
if (!googleApiClient.isConnected()){
googleApiClient.connect();
}
startLocationUpdates();
displayLocation2();
locationRequest = LocationRequest
.create()
.setInterval(1000)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
startLocationUpdates();
displayLocation();
}else {
checkLocationPermission();
}
}
#Override
public void onConnectionSuspended(int i)
{
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult)
{
}
#Override
public void onLocationChanged(Location location)
{
lastLocation = location;
displayLocation2();
}
public void checkLocationPermission()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
}
}
}
protected synchronized void buildGoogleApiClient()
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private void setupUiViews()
{
btnBooking = findViewById(R.id.bookingButton);
btnBooking.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Toast.makeText(Welcome.this, "Getting Cab", Toast.LENGTH_SHORT).show();
btnBooking.setText(R.string.gettingCab);
clicked = true;
getNearestDriver();
} else
{
if(!driverFound){
btnBooking.setText(R.string.callTaxi);
stopLocationUpdates();
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference1 = FirebaseDatabase.getInstance().getReference("Customer Request");
GeoFire geoFire1 = new GeoFire(databaseReference1);
geoFire1.removeLocation(userId);
Toast.makeText(Welcome.this, "Canceling Cab", Toast.LENGTH_SHORT).show();
if(driverMarker!=null){
driverMarker.remove();
}
clicked = false;
}
}
}
});
}
private void displayLocation()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null ){
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
location.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
{
#Override
public void onComplete(String key, DatabaseError error) {
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
}else{
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 15.0f));
}
}
});
}else{
Log.d("Error", "Cannot Get Your Location");
}
}
private void displayLocation2()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null ){
if(clicked == true){
if (marker != null){
marker.remove();
}
final Double lat = lastLocation.getLatitude();
final Double lng = lastLocation.getLongitude();
customersUnderService.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lat, lng), new GeoFire.CompletionListener()
{
#Override
public void onComplete(String key, DatabaseError error) {
if (marker != null) {
marker.remove();
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker)).title("You"));
}else{
marker = mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker)).title("You"));
}
}
});
}
}else{
Log.d("Error", "Cannot Get Your Location");
}
}
private void setupLocation()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RequestCode);
}
}else{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
}
}
}
private void createLocationRequest()
{
locationRequest = LocationRequest.create()
.setInterval(1500)
.setFastestInterval(500)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setSmallestDisplacement(0);
}
private boolean checkPlayServices()
{
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode, this, ResourceCode).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, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void startLocationUpdates()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
private int radius = 1;
private Boolean driverFound = false;
private void getNearestDriver()
{
geoQuery = onDuty.queryAtLocation(new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()), radius);
geoQuery.removeAllListeners();
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
String driverId = key;
if(!driverFound){
driverFound = true;
driverID = key;
DatabaseReference driverRef = FirebaseDatabase.getInstance().getReference().child("DriversWorking").child(driverId);
String customerId = FirebaseAuth.getInstance().getCurrentUser().getUid();
HashMap map = new HashMap();
map.put("customerRideId", customerId);
driverRef.updateChildren(map);
driverID = key;
btnBooking.setText(R.string.gettingTaxiLocation);
customersUnderService.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(lastLocation.getLatitude(), lastLocation.getLongitude()));
getDriverLocation();
driversOnDuty.child(key).removeValue();
}
}
#Override
public void onKeyExited(String key) {
}
#Override
public void onKeyMoved(String key, GeoLocation location) { }
#Override
public void onGeoQueryReady() {
if(!driverFound){
radius++;
getNearestDriver();
}
}
#Override
public void onGeoQueryError(DatabaseError error) {
}
});
}
private void getDriverLocation()
{
driverWorkingRef = driverWorkingRef.child(driverID).child("l");
driverListener = driverWorkingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLng = 0;
btnBooking.setText(R.string.driverComing);
if (map.get(0) != null)
{
locationLat = Double.parseDouble(map.get(0).toString());
driverLat = locationLat;
}
if (map.get(1) != null)
{
locationLng = Double.parseDouble(map.get(1).toString());
driverLng = locationLng;
}
LatLng driverLatLng = new LatLng(locationLat, locationLng);
if (driverMarker != null) {
driverMarker.remove();
}
driverMarker = mMap.addMarker(new MarkerOptions().position(driverLatLng).icon(BitmapDescriptorFactory.fromResource(R.drawable.carmarker)).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(driverLatLng, 15.0f));
Location myLoc = new Location("");
Location driverLoc = new Location("");
myLoc.setLatitude(lastLocation.getLatitude());
myLoc.setLongitude(lastLocation.getLongitude());
driverLoc.setLatitude(locationLat);
driverLoc.setLongitude(locationLng);
float distance = myLoc.distanceTo(driverLoc);
;
if (distance<100){
btnBooking.setText(R.string.driverReached);
}
}getDriverLocation();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onStop()
{
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
}
These are the errors in the Logcat.
06-04 17:39:10.550 13127-13127/com.matt.autozauser E/art: The String#value field is not present on Android versions >= 6.0
06-04 17:39:11.166 13127-13358/com.matt.autozauser E/HAL: PATH3 /odm/lib64/hw/gralloc.qcom.so
PATH2 /vendor/lib64/hw/gralloc.qcom.so
PATH1 /system/lib64/hw/gralloc.qcom.so
PATH3 /odm/lib64/hw/gralloc.msm8953.so
PATH2 /vendor/lib64/hw/gralloc.msm8953.so
PATH1 /system/lib64/hw/gralloc.msm8953.so
06-04 17:40:19.271 13127-13228/com.matt.autozauser E/NoopPersistenceManager: Caught Throwable.
java.lang.StackOverflowError: stack size 1037KB
at com.google.firebase.database.collection.zza.insert(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgj.zzb...[20]
You can add the following line in AndroidManifest.xml:
<uses-library android:name="org.apache.http.legacy" android:required="false"/>
Use com.firebase:geofire-android:2.1.1. Maybe it's a version problem. This solved it for me.
I had a similar problem, and it was resolved by running it in an emulator with Google Play enabled and updated. Basically create a new Virtual Device that has Google Play (not just Google API).
See This Question for details.

com.google.android.gms.location.LocationListener not working in my activity

I would like to retrieve the device position each time the user moves but the onLocationChanged callback does not work. could someone please help me? here is my code of my activity that manages the google map. Please note, I'm using the onLocationChanged from the Google Library com.google.android.gms.location.LocationListener
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.annotation.TargetApi;
import android.os.Looper;
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.widget.Button;
import android.widget.Toast;
import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.LocationCallback;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.proper_international.properinternationnal.R;
import com.proper_international.properinternationnal.activity.customer.BookingProviderActivity;
import com.proper_international.properinternationnal.activity.menus.HamburgerMenuProviderActivity;
import com.proper_international.properinternationnal.entities.Nettoyeur;
import com.proper_international.properinternationnal.miscs.UserEnum;
import com.proper_international.properinternationnal.miscs.Utilities;
import com.proper_international.properinternationnal.services.ActionAPIService;
import com.proper_international.properinternationnal.services.FCMNotificationService;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class ProviderToCustomerMapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private Button btnAccept, btnDecline;
FusedLocationProviderClient mFusedLocationClient;
SharedPreferences sharedpreferences;
String latLong, idReserve, from, login;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
LocationRequest mLocationRequest;
Marker mCurrLocationMarker;
private LatLng equipierPosition;
private LocationManager locationManager;
static int MY_REQUEST_CODE = 225;
private String provider_info;
boolean isGPSEnabled, isNetworkEnabled;
// The minimum distance to change updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
}
setContentView(R.layout.activity_provider_to_customer_maps);
btnAccept = (Button) findViewById(R.id.btnAccept);
btnDecline = (Button) findViewById(R.id.btnDecline);
sharedpreferences = getSharedPreferences(Utilities.MY_PREFERENCE, Context.MODE_PRIVATE);
if (getIntent() != null) {
latLong = getIntent().getStringExtra("latLng");
idReserve = getIntent().getStringExtra("idReserve");
from = getIntent().getStringExtra("from");
login = getIntent().getStringExtra("login");
}
// 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);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
runOnClick();
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Provider.toString())) {
btnDecline.setVisibility(View.INVISIBLE);
btnAccept.setText("Consulter son profile.");
}
btnDecline.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
String result = new declinerReservation().execute().get();
if (result.equals("true"))
Toast.makeText(ProviderToCustomerMapsActivity.this, "Merci!", Toast.LENGTH_LONG).show();
finish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
});
btnAccept.setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString())) {
try {
String result = new assignerReservation().execute().get();
if (result.equals("true")) {
String latLng = mLastLocation.getLatitude() + "," + mLastLocation.getLongitude();
String title = "Reservation A.";
String body = "Un Eest prêt à vous R.";
//Notification PUSH
boolean notSend = false;
while (notSend == false) {
notSend = new FCMNotificationService().execute(from, title, body, latLng, idReserve, sharedpreferences.getString(Utilities.EXTRA_LOGIN, "")).get();
}
startActivity(new Intent(ProviderToCustomerMapsActivity.this, HamburgerMenuProviderActivity.class));
finish();
} else {
Toast.makeText(ProviderToCustomerMapsActivity.this, "Dommage! Un autre Ea décroché cette O.", Toast.LENGTH_LONG).show();
finish();
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
} else {
Intent intent = new Intent(ProviderToCustomerMapsActivity.this, BookingProviderActivity.class);
String[] chaine = idReserve.split(",");
intent.putExtra("idReserver", chaine[0]);
intent.putExtra("login", chaine[1]);
startActivity(intent);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
public void runOnClick() {
// mGoogleApiClient = this;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(ProviderToCustomerMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ProviderToCustomerMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_CODE);
}
}
if (ActivityCompat.checkSelfPermission(ProviderToCustomerMapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ProviderToCustomerMapsActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
}
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Last known location. In some rare situations, it can be null.
if (location != null) {
// Logique pour gérer l'objet d'emplacement
mLastLocation = location;
}
}
});
mFusedLocationClient.getLastLocation().addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception ex) {
Log.e("getLastLocation", "onFailure: "+ex.getMessage());
}
}
);
}
private boolean isGooglePlayServicesAvailable() {
int status = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GoogleApiAvailability.getInstance().getErrorDialog(this, status, 0).show();
return false;
}
}
/**
* 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.
*/
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_REQUEST_CODE);
}
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_COARSE_LOCATION)) {
} else {
// do request the permission
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_REQUEST_CODE);
}
}
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
if (sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString())) {
btnAccept.setText("Ma liste de R");
btnAccept.setVisibility(View.INVISIBLE);
//String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
String userId = login;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId.replaceAll(".", "_"), new GeoLocation(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
String[] ll = latLong.split(",");
double latitude = Double.parseDouble(ll[0]);
double longitude = Double.parseDouble(ll[1]);
equipierPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position de l'e."));
geoFire.getLocation(userId.replaceAll(".", "_"), new LocationCallback() {
#Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("L'emplacement de la clé %s est [%f,%f]", key, location.latitude, location.longitude));
equipierPosition = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position de l'équipier."));
} else {
Log.d("Pas d'emplacement", String.format("Il n'y a pas d'emplacement pour la clé %s dans GeoFire", key));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Erreur produite", "Une erreur s'est produite lors de l'obtention de l'emplacement GeoFire: " + databaseError);
}
});
} else {
String userIds = login;
DatabaseReference refs = FirebaseDatabase.getInstance().getReference("ClientDisponible");
String[] ll = latLong.split(",");
double latitude = Double.parseDouble(ll[0]);
double longitude = Double.parseDouble(ll[1]);
GeoFire geoFire = new GeoFire(refs);
geoFire.setLocation(userIds.replaceAll(".", "_"), new GeoLocation(latitude, longitude));
equipierPosition = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position 0."));
geoFire.getLocation(userIds.replaceAll(".", "_"), new LocationCallback() {
#Override
public void onLocationResult(String key, GeoLocation location) {
if (location != null) {
System.out.println(String.format("L'emplacement de la clé %s est [%f,%f]", key, location.latitude, location.longitude));
equipierPosition = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(equipierPosition).title("Position 1."));
} else {
Log.d("Pas d'emplacement", String.format("Il n'y a pas d'emplacement pour la clé %s dans GeoFire:" + key));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Erreur obtention", databaseError.getMessage());
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
} else {
// Your app will not have this permission. Turn off all functions
// that require this permission or it will force close like your
// original question
}
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
mGoogleApiClient.connect();
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
// LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
com.google.android.gms.location.LocationCallback mLocationCallback = new com.google.android.gms.location.LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Position actuelle");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
};
};
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onResume() {
super.onResume();
runOnClick();
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
String userId = login;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.setLocation(userId.replaceAll(".","_"), new GeoLocation(location.getLatitude(), location.getLongitude()));
}
#Override
protected void onStop() {
super.onStop();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
String userId = login.replaceAll(".","_");
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("EDisponible");
if (!sharedpreferences.getString(Utilities.EXTRA_ROLE, "").equals(UserEnum.Customer.toString()))
ref = FirebaseDatabase.getInstance().getReference("ClientDisponible");
GeoFire geoFire = new GeoFire(ref);
geoFire.removeLocation(userId);
}
}
}
I was able to solve my problem by adding this line of code in the onConnected method:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
I had not used LocationServices because FusedLocationApi is deprecated.

Why my location data create a unique ID fields each time the location updates were stored in Firebase

I had create a Location Listener by FusedLocation. Each time when my logged auth user start to track their location, the location were write under the currentuser user-id but it keep added a different unique ID for each location that were written in the database. I need that 'location' in the same tree with my current login user description ('name' & 'type') and each time my current user have a location changed data, it will overwrite the data in the 'latitude' and 'longitude'. How I can reconstruct my code?
Here my screenshot of my database
my firebase database
Here my location.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
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.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* Created by AKMAL NIZAR ROSLE on 12/6/2017.
*/
public class DriverActivity extends AppCompatActivity implements
LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "DriverActivity";
private static final long INTERVAL = 1000 * 10;
private static final long FASTEST_INTERVAL = 1000 * 5;
private FirebaseAuth auth;
private DatabaseReference databaseReference;
Button btnFusedLocation;
TextView tvLocation, textViewUser;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
String mLastUpdateTime;
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
//get current user
if (auth.getCurrentUser() == null) {
startActivity(new Intent(DriverActivity.this, LoginActivity.class));
finish();
}
databaseReference = FirebaseDatabase.getInstance().getReference();
Log.d(TAG, "onCreate ...............................");
//show error dialog if GoolglePlayServices not available
if (!isGooglePlayServicesAvailable()) {
finish();
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
setContentView(R.layout.activity_driver);
FirebaseUser user = auth.getCurrentUser();
textViewUser = (TextView) findViewById(R.id.textViewUser);
textViewUser.setText("Welcome"+" "+user.getEmail());
tvLocation = (TextView) findViewById(R.id.tvLocation);
btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
btnFusedLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
updateUI();
}
});
}
#Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart fired ..............");
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
mGoogleApiClient.disconnect();
Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
}
private boolean isGooglePlayServicesAvailable() {
final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "This device is not supported.");
}
return false;
}
return true;
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Connection failed: " + connectionResult.toString());
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
saveToFirebase();
updateUI();
}
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mLocations = new HashMap();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
mLocations.put("location", mCoordinate);
databaseReference.child(user.getUid()).push().setValue(mLocations);
}
private void updateUI() {
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
"Latitude: " + lat + "\n" +
"Longitude: " + lng + "\n" +
"Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
"Provider: " + mCurrentLocation.getProvider());
} else {
Log.d(TAG, "location is null ...............");
}
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
Log.d(TAG, "Location update resumed .....................");
}
}
}
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mLocations = new HashMap();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
mLocations.put("location", mCoordinate);
databaseReference.child(user.getUid()).push().setValue(mLocations);
}
Just remove the push() method in your setValue database operation:
private void saveToFirebase() {
FirebaseUser user = auth.getCurrentUser();
Map mCoordinate = new HashMap();
mCoordinate.put("latitude", mCurrentLocation.getLatitude());
mCoordinate.put("longitude", mCurrentLocation.getLongitude());
databaseReference.child(user.getUid() + "/location").setValue(mCoordinate);
}
The push() method generates a new node with an unique key to your database reference.

Requesting permission at run time - Android

I was trying to create one demo app using Google Play services location. It's working fine in my mobile phone but it shows the location for short period of time. However, the emulator didn't display any location. Any suggestion is appreciated..
The current version of my Emulator - 6.0 and targetSdkVersion 24
Here is the MainActivity Code
package com.example.android.mylocation;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
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 java.io.IOException;
import java.util.jar.Manifest;
import android.Manifest.permission;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
private final String LOG_TAG = "MyLocation";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private TextView mTextView;
public static final int MY_PERMISSION_REQUEST_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** Create Google Api Client */
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
Log.v(LOG_TAG, "Google Api Client Created");
mTextView = (TextView) findViewById(R.id.location);
}
/** This method will connect the Google Api Client */
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
Log.v(LOG_TAG, "Connect the Google Play Services");
}
/** This method will disconnect the Google Api Client */
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.v(LOG_TAG, "Google Play Services Connected");
try{
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Log.v(LOG_TAG, "Priority High Accuracy");
mLocationRequest.setInterval(5000);
/** Request the permissions you need */
if (ContextCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
Log.v(LOG_TAG, "Self Permission is not Granted");
//Request the permission
ActivityCompat.requestPermissions(this, new String[] {permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_REQUEST_LOCATION);
}
}
catch(Exception e){
Log.v(LOG_TAG, e.toString());
}
/* try {
//mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
catch(SecurityException e){
Log.v(LOG_TAG, e.toString());
}*/
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.v(LOG_TAG, "User permission");
switch (requestCode) {
case MY_PERMISSION_REQUEST_LOCATION: {
Log.v(LOG_TAG, "Check the User Response");
//If request is cancelled, the request arrays are empty
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
try {
Log.v(LOG_TAG, "Check the user location");
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
//mTextView.setText(location.toString());
}
catch(SecurityException e){
Log.v(LOG_TAG, e.toString());
}
}
else {
Log.v(LOG_TAG, "Permission denied");
}
return;
}
}
}
#Override
public void onConnectionSuspended(int i) {
/*if (!mGoogleApiClient.isConnected()){
mGoogleApiClient.connect();
}*/
Log.v(LOG_TAG, "Connection Suspended");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.v(LOG_TAG, connectionResult.getErrorMessage());
}
#Override
public void onLocationChanged(Location location) {
Log.v(LOG_TAG, "Location Change Detected");
mTextView.setText(location.toString());
}
}

Categories

Resources