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

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.

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 pass the current lat long values from one class to another activity in Android?

I am using googleAPIClient to get the current lat long values using Location. I am getting the values of both my current lat and long in a separate class. I need to pass these current lat and long values inside my MapsActivity ( GoogleMap Activity), Since I have already created the object for the another class, from which I need to get the values, I don't know how to pass the values to this activity from the class.
Here's what I have tried. This is the class which I have created to get the current lat long values:
CurrentValues.java:
public class CurrentValues implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final String TAG = CurrentValues.class.getSimpleName();
private Context context;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private long UPDATE_INTERVAL = 2 * 1000; /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */
public CurrentValues( Context context){
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(context, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
#Override
public void onLocationChanged(Location location) {
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
private boolean checkLocation() {
if(!isLocationEnabled())
showAlert();
return isLocationEnabled();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
private boolean isLocationEnabled() {
mLocationManager = (LocationManager)context. getSystemService(Context.LOCATION_SERVICE);
return mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(context);
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 paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
});
dialog.show();
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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, (com.google.android.gms.location.LocationListener) context);
Log.d("reque", "--->>>>");
}
}
Now I need to pass the lat long values I got from this class to MapsActivity. Since I had already created object for the currentvalues class here in this activity, I don't know how to pass the value from there to here.
Here's my MapActivity (GoogleMap Activity)
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private CurrentValues currentValues;
private Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
mapFragment.getMapAsync(this);
}
/**
* 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;
// // 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"));
//
// LatLng chennai = new LatLng(13.06,80);
// mMap.addMarker(new MarkerOptions().position(chennai).title("Marker in Chennai"));
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 8f));
// creating object for currentValues class
CurrentValues currentValues = new CurrentValues(this);
}
}
I don't know how to proceed after this to pass the lat long values here. How can I proceed?

My app does not check location.addOnCompleteListener() and crashes

I am trying to make a location tracking android app. I am getting problem with location.addOnCompleteListener in getDeviceLocation() class. Android studio does not check this and the app crashes here. Following is the code i've written...
import...
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleMap mMap;
final int LOCATION_REQUEST_CODE = 1;
Location mLastLocation;
//FusedLocationProviderClient mFusedLocationClient;
LocationRequest mLocationRequest;
GoogleApiClient googleApiClient;
public static double longitude = 0.0d;
public static double latitude = 0.0d;
private FusedLocationProviderClient mFusedLocationProviderClient;
private long UPDATE_INTERVAL = 1000; /* 10 secs */
private long FASTEST_INTERVAL = 1000; /* 2 sec */
public static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
public static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private boolean mLocationPermissionGranted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setupContents();
if (!isNetworkConnected()){
Toast.makeText(this, "You are offline!!!", Toast.LENGTH_SHORT).show();
finish();
return;
}
getLocationPermission();
//startLocationUpdates();
}
public void initMap() {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
// mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFragment.getMapAsync(this);
}
public void setupContents() {
btnEnd = findViewById(R.id.btnEnd);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Toast.makeText(this, "Map is ready", Toast.LENGTH_SHORT).show();
if (mLocationPermissionGranted) {
getDeviceLocation();
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);
}
}
public void getLocationPermission(){
String [] permissions={Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted=true;
showGPSDisabledAlertToUser();
initMap();
} else {
ActivityCompat.requestPermissions(this,permissions,LOCATION_PERMISSION_REQUEST_CODE);
}
}
else {
ActivityCompat.requestPermissions(this,permissions,LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
mLocationPermissionGranted=false;
switch (requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length>0){
for(int i=0;i<grantResults.length;i++){
if(grantResults[i]!=PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted=false;
return;
}
}
mLocationPermissionGranted=true;
showGPSDisabledAlertToUser();
initMap();
}
}
}
}
private void getDeviceLocation(){
mFusedLocationProviderClient=LocationServices.getFusedLocationProviderClient(this);
try {
if(mLocationPermissionGranted){
Task<Location> location=mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(this,new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Location currentLocation= (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),12);
}
else
Toast.makeText(MapsActivity.this, "Unable to get current location", Toast.LENGTH_SHORT).show();
}
});
}
}catch (SecurityException ex){
}
}
private void moveCamera(LatLng latLng,float zoom){
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));
}
private void showGPSDisabledAlertToUser() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
String locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
// Call your Alert message
Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
Toast.makeText(this, "Please turn on your location", Toast.LENGTH_SHORT).show();
}
else if (locationProviders == null || locationProviders.equals("")) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
else
return;
}
#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(12));*/
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
}
The problem arise during debugging is source code does not match the byte code after executing this statement location.addOnCompleteListener(this,new OnCompleteListener(){.
The gradle dependencies are:
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-vision:15.0.2'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
stacktrace messages are given below:
09-08 22:47:43.485 30955-30955/? E/Zygote: v2
09-08 22:47:43.487 30955-30955/? E/Zygote: accessInfo : 0
09-08 22:47:47.056 30955-30993/com.example.muzammil.maptestingproject E/cr_VariationsUtils: Failed reading seed file "/data/user/0/com.example.muzammil.maptestingproject/app_webview/variations_seed_new": /data/user/0/com.example.muzammil.maptestingproject/app_webview/variations_seed_new (No such file or directory)
09-08 22:47:58.366 30955-30955/com.example.muzammil.maptestingproject E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib, /vendor/lib]]
09-08 22:48:14.641 30955-30955/com.example.muzammil.maptestingproject E/art: The String#value field is not present on Android versions >= 6.0
09-08 22:48:15.379 30955-30955/com.example.muzammil.maptestingproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.muzammil.maptestingproject, PID: 30955
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.muzammil.maptestingproject.Activities.MapsActivity$3.onComplete(MapsActivity.java:222)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
Anyone having the solution help please. Thanks in advance

i am getting zero values of longitude and latitude in google maps in android studio

Here is my MapsActivity.java code, I am getting zero values for longitude and latitude after placing a marker on map and after calling getCurrentlocation(). What is going wrong?
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMarkerDragListener,
GoogleMap.OnMapLongClickListener,
View.OnClickListener {
//Our Map
private GoogleMap mMap;
//To store longitude and latitude from map
private double longitude;
private double latitude;
//Buttons
private ImageButton buttonSave;
private ImageButton buttonCurrent;
private ImageButton buttonView;
//Google ApiClient
private GoogleApiClient googleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
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);
mapFragment.getMapAsync(this);
//Initializing googleapi client
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
//Initializing views and adding onclick listeners
buttonSave = (ImageButton) findViewById(R.id.buttonSave);
buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
buttonView = (ImageButton) findViewById(R.id.buttonView);
buttonSave.setOnClickListener(this);
buttonCurrent.setOnClickListener(this);
buttonView.setOnClickListener(this);
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
//Getting current location
private void getCurrentLocation() {
mMap.clear();
//Creating a location object
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;
}
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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
//Getting longitude and latitude
longitude = location.getLongitude();
latitude = location.getLatitude();
//moving the map to location
moveMap();
}
}
//Function to move the map
private void moveMap() {
//String to display current latitude and longitude
String msg = latitude + ", "+longitude;
//Creating a LatLng Object to store Coordinates
LatLng latLng = new LatLng(latitude, longitude);
//Adding marker to map
mMap.addMarker(new MarkerOptions()
.position(latLng) //setting position
.draggable(true) //Making the marker draggable
.title("Current Location")); //Adding a title
//Moving the camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Animating the camera
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
//Displaying current coordinates in toast
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.setOnMarkerDragListener(this);
mMap.setOnMapLongClickListener(this);
}
#Override
public void onConnected(Bundle bundle) {
getCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onMapLongClick(LatLng latLng) {
//Clearing all the markers
mMap.clear();
//Adding a new marker to the current pressed position
mMap.addMarker(new MarkerOptions()
.position(latLng)
.draggable(true));
String msg = latitude + ", "+longitude;
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
//Getting the coordinates
latitude = marker.getPosition().latitude;
longitude = marker.getPosition().longitude;
//Moving the map
moveMap();
}
#Override
public void onClick(View v) {
if(v == buttonCurrent){
getCurrentLocation();
moveMap();
}
}
}
GetLastLocation only returns a location if one is available. 99% of the time it won't be. Use requestLocationUpdates or requestSingleUpdate to ensure a location is acquired (note both of these are asynchronous functions, as getting a location takes time).
Use Request Location Updates better
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(15 * 1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setSmallestDisplacement(0);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener);
}
}
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//do whatever you want here
}
}
};
Don't Forget to add onDestory Method
#Override
protected void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener);
mGoogleApiClient.disconnect();
}
}

Categories

Resources