Problem: Attempt to invoke virtual method 'double android.location.Location.getLatitude() - java

I'm trying to display my current location but I have this problem. I don't know in what part is the error, I put Common.mLastLocation, AND ACCESS_COARSE_LOCATION. Could you help me, please. My Location is resturn NULL, I recently changed my library 'com.google.android.gms:play-services-maps:11.8.0'. My logcat is: Attempt to invoke virtual method 'double android.location.Location.getLatitude()
First part:
public class Home_rider extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener ,
OnMapReadyCallback{
SupportMapFragment mapFragment;
FusedLocationProviderClient fusedLocationProviderClient;
LocationCallback locationCallback;
//Location
private GoogleMap mMap;
private static final int MY_PERMISSION_REQUEST_CODE = 7192; // MY Birthday
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 300193; // MY CODE
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
private static int UPDATE_INTERVAL = 5000; // 5 secs
private static int FATEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference ref;
GeoFire geoFire;
Marker mUserMarker,markerDestination;
boolean isDriverFound=false;
String driverId="";
int radius = 1; //1km
int distance = 1; //3km
private static final int LIMIT = 3;
//BottomSheet
ImageView imgExpandable;
BottomSheetRiderFragment mBottomSheet;
Button btnPickupRequest;
//Presense system
DatabaseReference driversAvailable;
//Send Alert
IFCMService mService;
PlaceAutocompleteFragment place_location,place_destination;
String mPlaceLocation,mPlaceDestination;
//New Update Information
CircleImageView imageAvatar;
TextView txtRiderName,txtStars;
//Declare FireStorage to upload avatar
FirebaseStorage storage;
StorageReference storageReference;
Get location:
private void setUpLocation() {
//Copy code from Driver APP
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}
else
{
buildLocationCallBack();
createLocationRequest();
displayLocation();
}
}
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;
}
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null)
{
//Create LatLng from mLastLocation and this is center point
LatLng center = new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude());
//Distance in meters
//Heading 0 is northside , 90 is east, 180 is south and 270 is west
//Base compat
LatLng northSide = SphericalUtil.computeOffset(center,100000,0);
LatLng southSide = SphericalUtil.computeOffset(center,100000,180);
LatLngBounds bounds = LatLngBounds.builder()
.include(northSide)
.include(southSide)
.build();
place_location.setBoundsBias(bounds);
place_destination.setBoundsBias(bounds);
//Presense System
driversAvailable = FirebaseDatabase.getInstance().getReference(Common.driver_tbl);
driversAvailable.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//If have any change from Drivers table , we will reload all drivers available
loadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude()));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
loadAllAvailableDriver(new LatLng(Common.mLastLocation.getLatitude(),Common.mLastLocation.getLongitude()));
Log.d("MoaguiTaxi",String.format("No se pudo encontrar su ubicación : %f / %f", latitude, longitude));
}
else
{
Log.d("MoaguiTaxi","No se pudo encontrar su ubicación");
}
}
});
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
boolean isSucces = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(this,R.raw.my_map_style)
);
if (!isSucces)
Log.e("ERROR","No se cargó el mapa");
}
catch (Resources.NotFoundException ex)
{
ex.printStackTrace();
}
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setZoomGesturesEnabled(true);
mMap.setInfoWindowAdapter(new CustomInfoWindow(this));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
//First , check markerDestination
//If is not null , just remove available marker
if (markerDestination != null)
markerDestination.remove();
markerDestination = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.destination_marker))
.position(latLng)
.title("Destination"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,15.0f));
//Show bottom sheet
BottomSheetRiderFragment mBottomSheet = BottomSheetRiderFragment.newInstance(String.format("%f,%f",mLastLocation.getLatitude(),mLastLocation.getLongitude()),
String.format("%f,%f",latLng.latitude,latLng.longitude)
,true);
mBottomSheet.show(getSupportFragmentManager(),mBottomSheet.getTag());
}
});
//Copy code from Driver APP
if (ActivityCompat.checkSelfPermission(Home_rider.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(Home_rider.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
return;
}
buildLocationCallBack();
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest,locationCallback, Looper.myLooper());
}
}

It is because you are using mLastLocation.getLatitude() instead of Common.mLastLocation.getLatitude() in your setOnMapClickListener.
The error is basically getLatitude() is being called on null reference.

Related

Why is my code not getting the latitude and longitude of my location in google map

I want to create a database reference in firebase whenever a particular user is online and at the same time store the latitude and longitude of that online user into firebase database by using Geofire. I dont know why my longitude and latitude is returning null even when there is an online user.It's becoming so frustrating as I don't really know what is the issue and I have check so many suggestions from stack overflow and still can't solve it. Your helps will be really appreciated
Here is the code
public class DriversMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drivers_maps);
driverSetting = findViewById(R.id.driver_maps_setting);
logoutBtn = findViewById(R.id.driver_maps_logout);
mAuth = FirebaseAuth.getInstance();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.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) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
// if (getApplicationContext()!=null){
if (lastLocation !=null){
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.setLocation(userID,new GeoLocation(location.getLatitude(),location.getLongitude()));
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.removeLocation(userID);
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(DriversMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(DriversMapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
}
return true;
}
}

NullPointerException error on an Android-GeoFire project

This is the error I'm getting: java.lang. Attempt to call the virtual method 'double android.location.Location.getLatitude()' on a null object reference results in a NullPointerException.Can anyone guide me on how to achieve this?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks ,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
private ActivityMapsBinding binding;
private static final int MY_PERMISSION_REQUEST_CODE =71922 ;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 300193;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Location mLastLocation ;
private static int UPDATE_INTERVAL =5000;
private static int FARTEST_INTERVAL =5000;
private static int DISPLACEMENT =10;
Marker marker;
DatabaseReference ref ;
GeoFire geoFire;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 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);
ref = FirebaseDatabase.getInstance().getReference("Test");
setupLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case MY_PERMISSION_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if(checkPlayServices())
{
buildGoogleApiCLient();
createLocationRequest();
displayLocation();
}
}
break;
}
}
private void setupLocation() {
try {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PERMISSION_REQUEST_CODE);
}
else {
if(checkPlayServices())
{
buildGoogleApiCLient();
createLocationRequest();
displayLocation();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void displayLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED )
{
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if(mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Log.d("EDMDEV",String.format("your location was changed: %f %f ",latitude,longitude));
// upDate to firebase
geoFire.setLocation("You", new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if(marker != null){
marker.remove(); //remove old marker
marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude,longitude))
.title("Ele"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),12.0f));
}
}
});
}
else {
Log.d("EDMDEV","cannot get ur location");
}
}
private void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FARTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void buildGoogleApiCLient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS)
{
if(GooglePlayServicesUtil.isUserRecoverableError(resultCode))
GooglePlayServicesUtil.getErrorDialog(resultCode,this,PLAY_SERVICES_RESOLUTION_REQUEST).show();
else {
Toast.makeText(this, "this device is not support", Toast.LENGTH_SHORT).show();
finish();
}
return false ;
}
return true;
}
/**
* 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;
// LatLng syd = new LatLng( -34,151);
// mMap.addMarker(new MarkerOptions().position(syd).title("mar in syd"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(syd));
//Create area
LatLng village = new LatLng(35.7533,-122.4056);
mMap.addCircle(new CircleOptions()
.center(village)
.radius(500) // in meter
.strokeColor(Color.BLUE)
.fillColor(0x220000FF)
.strokeWidth(5.0f)
);
// 0.5f = 0.5km = 500 m
GeoQuery geoQuery = geoFire .queryAtLocation(new GeoLocation(village.latitude,village.longitude),0.5f);
geoQuery.addGeoQueryEventListener(new GeoQueryEventListener() {
#Override
public void onKeyEntered(String key, GeoLocation location) {
sendNotification("EDKDD",String.format("%s entered village area ",key ));
}
#Override
public void onKeyExited(String key) {
sendNotification("EDKDD",String.format("%s no longer village area ",key ));
}
#Override
public void onKeyMoved(String key, GeoLocation location) {
sendNotification("Move",String.format("%s moved within the village area [%f/%f]",key,location.latitude, location.longitude ));
}
#Override
public void onGeoQueryReady() {
}
#Override
public void onGeoQueryError(DatabaseError error) {
Log.e("Error","" + error);// 36.46
}
});
}
private void sendNotification(String title, String content) {
Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle(title)
.setContentText(content);
NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this,MapsActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_IMMUTABLE);
builder.setContentIntent(contentIntent);
Notification notification = builder.build();
notification.flags = Notification.DEFAULT_SOUND;
notificationManager.notify(new Random().nextInt(),notification);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdate();
}
private void startLocationUpdate() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED )
{
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,locationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
displayLocation();
}
}
java.lang.NullPointerException Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.newapp.elephantapplication, PID: 3267
java.lang.NullPointerException: Attempt to invoke virtual method 'com.firebase.geofire.GeoQuery com.firebase.geofire.GeoFire.queryAtLocation(com.firebase.geofire.GeoLocation, double)' on a null object reference
at com.newapp.elephantapplication.MapsActivity.onMapReady(MapsActivity.java:224)
at com.google.android.gms.maps.zzat.zzb(com.google.android.gms:play-services-maps##18.0.0:1)
at com.google.android.gms.maps.internal.zzaq.zza(com.google.android.gms:play-services-maps##18.0.0:5)
at com.google.android.gms.internal.maps.zzb.onTransact(com.google.android.gms:play-services-maps##18.0.0:3)
at android.os.Binder.transact(Binder.java:387)
at eg.aZ(:com.google.android.gms.dynamite_mapsdynamite#220920047#22.09.20 (040308-0):2)
at com.google.maps.api.android.lib6.impl.bk.run(:com.google.android.gms.dynamite_mapsdynamite#220920047#22.09.20 (040308-0):1)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Just getting used to Java and Android and I've got the above error.
Can anyone guide me on how to achieve this?

How to draw a route from current location to a markerpoint on Android Google Maps?

I'm new creating apps and I want to show a drawn route in a Google Map starting from the current location. I've just found how to get the current location, but now I'm stuck in the second part, which is drawing the route from the current location to another marker point.
Here is my code:
`public class Trazo_Rutas extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location lastLocation;
Marker userLocation;
private static final int Request_User_Location_Code = 99;
PlaceAutocompleteFragment placeAutoComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trazo__rutas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
//AutoComplete search bar
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
// 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);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//get latlong for corners for specified place
LatLng corner1 = new LatLng(25.64379, -103.60966);
LatLng corner2 = new LatLng(25.64317, -103.20935);
LatLng corner3 = new LatLng(25.43872, -103.61104);
LatLng corner4 = new LatLng(25.43748, -103.20866);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(corner1);
builder.include(corner2);
builder.include(corner3);
builder.include(corner4);
LatLngBounds bounds = builder.build();
//add them to builder
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
// 20% padding
int padding = (int) (width * 0.20);
//set latlng bounds
mMap.setLatLngBoundsForCameraTarget(bounds);
//move camera to fill the bound to screen
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission() {
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
}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Se requieren Permisos de Google", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if (userLocation != null) {
userLocation.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Tu ubicación");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
userLocation = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}`
My concern is that I don't know how to implement the other marker and draw the route.
Thank you.

Receive location updates even when phone is locked?

I have been trying to receive location updates when my phone is locked I am using a service that is launched by my main activity. I receive location updates when the application is open just fine but when locking the phone the service continues to run but the location stored is the same every time.
import static com.example.kromby.mapsapplication.featureOptions.date;
public class BackgroundLocationUpdate extends Service implements GoogleApiClient.ConnectionCallbacks, LocationListener {
// I've removed code that does not relate to the question so please ignore most imports.
private GoogleApiClient mClient;
private boolean connected = false;
private LocationRequest mLocationRequest;
public static List<LatLng> globalLatLng = Collections.synchronizedList(new ArrayList<LatLng>());
public static GoogleMap mMap;
Location mLastLocation;
private static double latitude;
private static double longitude;
public LatLng mLatLng = new LatLng(latitude, longitude);
private static final String TAG = "MapActivity";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#TargetApi(Build.VERSION_CODES.O)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
#Override
public void run() {
buildGoogleApiClient();
}
};
Runnable q = new Runnable() {
#Override
public void run() {
long p = System.currentTimeMillis() + 4000;
boolean continueLooping = true;
while (continueLooping) {
if (System.currentTimeMillis() >= p) {
locationUpdates();
continueLooping = false;
}
}
}
};
Thread mThread = new Thread(r);
Thread mThreadTwo = new Thread(q);
mThread.start();
mThreadTwo.start();
return Service.START_STICKY;
}
public void locationUpdates() {
long i = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() == i) {
i = System.currentTimeMillis() + 3000;
// Checks that the application has user permissions to location.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mClient);
// Once the phone is locked this will return the same location each time and not change.
Log.d(TAG, "Client is working " + mClient.isConnected() + "\n Current mLastLocation LatLng " + mLastLocation.getLatitude() + "," + mLastLocation.getLatitude());
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Log.d(TAG, "latitude = " + String.valueOf(latitude) );
mLatLng = new LatLng(latitude, longitude);
globalLatLng.add(mLatLng);
Log.d(TAG, "Global List = " + globalLatLng);
}
}
}
protected synchronized void buildGoogleApiClient() {
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API).build();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
connected = true;
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(3000);
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) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
mClient.connect();
}
#Override
public void onDestroy() {
Log.i(TAG, "OnDestroy method called");
}
}
My aim is to receive a location save that into a Latlng list and store it into a text file, that can be read and shown on the map in a polyline. I am running them on two seperate threads because googles api clients does not finish so it wont reach any other code.

Trouble with 'System services not available to Activities before onCreate()'

I'm having some trouble and could with some help. I've got a MapsActivity and a LocationHelper class but when loading the MapsActivity I get presented with the errors listed below.
MapsActivity -
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;
private GoogleMap mMap;
private LocationHelper locationHelper;
private LatLng location;
private boolean onCreateFinished = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onCreateFinished = true;
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
//instantiates LocationHelper for use in this activity
locationHelper = new LocationHelper(this);
//runs startConnection from LocationHelper class
locationHelper.startConnection();
//starts map
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
//sets map markers
public void setMapMarkers(){
//runs checkLocation from LocationHelper class
locationHelper.checkLocation();
location = new LatLng(locationHelper.mLatitude, locationHelper.mLongitude);
LatLng currentLocation = new LatLng(location.latitude, location.longitude);
mMap.addMarker(new MarkerOptions().position(currentLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
}
#Override
protected void onStart() {
locationHelper.mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
if(onCreateFinished == true){
setMapMarkers();
}else{
Toast.makeText(this, "onCreate not finished..", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStop() {
locationHelper.mGoogleApiClient.disconnect();
//LocationManager.removeUpdates();
super.onStop();
}
LocationHelper class -
public class LocationHelper extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
//private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
//private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;
GoogleApiClient mGoogleApiClient;
private LocationManager mLocationManager;
//private Location mLastLocation;
private LocationListener mLocationListener;
public double mLatitude;
public double mLongitude;
private Context context;
//constructor
public LocationHelper(Context context) {
//saves the context received from activity that instantiates LocationHelper into a local variable
this.context = context;
}
public void startConnection() {
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
public void checkLocation(){
//gets system service from LocationManager
mLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
//checks permissions
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}
mLocationListener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//checks if GPS is enabled
if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
if(mLocationListener != null){
if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}
if (mLocationManager != null) {
location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
Toast.makeText(getApplicationContext(), "GPS - " + String.valueOf(mLatitude) + "," + String.valueOf(mLongitude), Toast.LENGTH_SHORT).show();
}
}
}
}
//checks if internet is enabled
else if(mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
if(mLocationManager != null){
location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null){
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
Toast.makeText(getApplicationContext(), "NETWORK - " + String.valueOf(mLatitude) + "," + String.valueOf(mLongitude), Toast.LENGTH_SHORT).show();
}
}
}
//method for setting location request parameters
setLocationRequest();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void setLocationRequest(){
//sets locationrequest parameters
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
public double getLatitudeForNote() {
return mLatitude;
}
public double getLongitudeForNote(){
return mLongitude;
}
}
Error -
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a8460p.locationotes, PID: 1715
java.lang.RuntimeException: Unable to resume activity {com.example.a8460p.locationotes/com.example.a8460p.locationotes.MapsActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3160)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2529)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:5300)
at com.example.a8460p.locationotes.LocationHelper.checkLocation(LocationHelper.java:66)
at com.example.a8460p.locationotes.MapsActivity.setMapMarkers(MapsActivity.java:71)
at com.example.a8460p.locationotes.MapsActivity.onResume(MapsActivity.java:88)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259)
at android.app.Activity.performResume(Activity.java:6361)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3149)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3191) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2529) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:234) 
at android.app.ActivityThread.main(ActivityThread.java:5526) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Thanks in advance for any help!
Step #1: Delete extends Activity from LocationHelper. This is not an activity.
Step #2: Use the context for your call to getSystemService() inside of LocationHelper.
Step #3: Decide whether you are going to use Android's LocationManager or LocationRequest from the Play Services SDK, and get rid of all the code associated with the one that you are not going to use.
You need to initialize your LocationHelper instance after onCreate completed. You can move related code into onMapReady() method.

Categories

Resources