How to use getCurrentLocation of fused location provider client? - java

I am new for Android coding, and have writen a code to get location of Android Device but failed. Nothing changed (e.g. mLastKnownLocation or cityName) after runing, and no expception. I have already checked permission and build.gradle. Could you give me advices to implement it?
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY,cancellationToken);
//Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>(){
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Obtain the current location of the device
mLastKnownLocation = task.getResult();
String currentOrDefault = "Current";
if (mLastKnownLocation != null) {
Log.d(TAG, "Get current location");
} else {
Log.d(TAG, "Current location is null. Using defaults.");
currentOrDefault = "Default";
// Set current location to the default location
mLastKnownLocation = new Location("");
mLastKnownLocation.setLatitude(mDefaultLocation.latitude);
mLastKnownLocation.setLongitude(mDefaultLocation.longitude);
}
String city = "CorrectCity";
try {
List<Address> address =
geocoder.getFromLocation(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude(), 1);
if(address.isEmpty())
city = "No_city";
else{
Address target = address.get(0);
if(target.getLocality()!=null)
city = target.getLocality();
else
city = target.getAdminArea();}
} catch (IOException e) {
Log.e("Exception: %s", e.getMessage());
}
cityName = city;
// Show location details on the location TextView
String msg = currentOrDefault + " Location: " +
Double.toString(mLastKnownLocation.getLatitude()) + ", " +
Double.toString(mLastKnownLocation.getLongitude())+ " " +
cityName;
locationTextView.setText(msg);
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
/*mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);*/
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
cityName = "ErrorCity";
}
}
}

You can get your last known location using the code below
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
// your last known location is stored in `location`
}
});
refer: https://developer.android.com/training/location/retrieve-current
Using Location Manager
LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
mMap.clear();
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Me"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
#Override
public void onProviderEnabled(#NonNull String provider) {
}
#Override
public void onProviderDisabled(#NonNull String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

Related

Location is null - Android

I'm creating an app, where I want to get my current location. I want to get location only once, when user opens the app. I don't need any updates, while app is open.
Here's my code.
public class MainActivity extends AppCompatActivity {
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
return;
}
fetchLocation();
}
private void fetchLocation() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(600);
mLocationRequest.setFastestInterval(300);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.d("MyTag", "Location is null");
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
Log.d("MyTag", location.getLatitude() + " " + location.getLongitude());
}
}
}
};
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.d("MyTag", "GoogleAPIClient connected");
Task<Location> task = LocationServices.getFusedLocationProviderClient(MainActivity.this).getLastLocation();
task.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location == null) {
LocationServices.getFusedLocationProviderClient(MainActivity.this).requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} else {
Log.d("MyTag", "My location is: " + location.getLatitude() + " : " + location.getLongitude());
}
}
}).addOnFailureListener(MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("MyTag", "Error message: " + e.getMessage());
}
});
}
#Override
public void onConnectionSuspended(int i) {
Log.d("MyTag", "GoogleAPIClient connection suspended");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(MainActivity.this, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
})
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
LocationServices.getFusedLocationProviderClient(MainActivity.this).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Log.d("MyTag", "My locations is: " + location.getLatitude() + " : " + location.getLongitude());
} else {
Log.d("MyTag", "My locations is null");
}
}
});
}
}
I watched almost all stackoverflow answers, but nothing helped. I don't know where I'm doing wrong.
I read that the fused Location Provider will only maintain background location if at least one client is connected to it. I'm connecting GoogleApiClient. If you see logs, it connects successfully, but then nothing happens. Thank you.
My logs:
-- My locations is null
-- GoogleAPIClient connected

Android - How to request location update in the new API?

I was playing a bit around the new location API from google (to get latitude and longitude values):
private void getLastLocation(){
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
try {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), String.valueOf(latitude) + "/" + String.valueOf(longitude), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot get location", Toast.LENGTH_LONG).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("LocationFetch", "Error trying to get last GPS location");
e.printStackTrace();
}
});
} catch (SecurityException e){
Log.d("LocationFetch", "Permission missing");
}
}
When I first tested this code, the location was always returning null. However, after opening Instagram (which did a location update on my phone - the geo icon appeared briefly), the location was returning my relevant longitude and latitude values.
How do I request a location update on my app using the new API to prevent location from being null or retrieve very old locations? (getLastLocation() is not enough, possibly LocationRequest?)
It is worth noting that I do not want interval updates, I want for it to happen within an Android Service when invoked once.
Firstly add this implementation in your build.gradle file
implementation 'com.google.android.gms:play-services-location:11.2.0'//include the latest version of play services
After that implement, (implements LocationListener) in your activity or fragment and after that implement its function and then
call this method in your onCreate() getLocation();
and then in this function add these lines
protected void getLocation() {
if (isLocationEnabled(MainActivity.this)) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
else
{
//prompt user to enable location....
//.................
}
}
After that in your onLocationChanged(Location location)
add these lines of code
#Override
public void onLocationChanged(Location location) {
//Hey, a non null location! Sweet!
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
and you are set to go!!!!
Cheers Happy Coding
It's work for me. Based on Official docs, every 10 seconds updates the Toast and shows your location:
private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
#Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
private void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
}
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
add bellow codes to onCreate method:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(2*5000);
locationCallback=new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// if (location != null) {
String Lat = String.valueOf(location.getLatitude());
String Lon = String.valueOf(location.getLongitude());
Toast.makeText(getApplicationContext(), Lat + " - " + Lon, Toast.LENGTH_SHORT).show();
// }
}
}
};
Try this code.
In gradle
implementation 'com.google.android.gms:play-services-location:16.0.0'
In code
private void turnGPSOn() {
LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
settingsBuilder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
.checkLocationSettings(settingsBuilder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response =
task.getResult(ApiException.class);
if (gps.canGetLocation()) {
lat = String.valueOf(gps.getLatitude());
lon = String.valueOf(gps.getLongitude());
}
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException =
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(SignupActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
}

Location Class returning empty location

I'm newcomer in Android development and I wish someone could help me.
My problem is as follow:
gradle
dependencies {
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.android.gms:play-services-location:15.0.1'
}
MainActivity
[...]
local = (CheckBox) findViewById(R.id.local_checkbox);
local.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DEBUG_INFO","CLICKED");
GPSTracker g = new GPSTracker(MainActivity.this);
if (((CheckBox) v).isChecked()) {
Log.v("DEBUG_INFO","CHECKED");
CheckGpsStatus();
if (GpsStatus == true) {
isLocated = true;
Location l = g.getLocation();
if ((l != null) && (isLocated == true)) {
lat = g.getLocation().getLatitude();
lon = g.getLocation().getLongitude();
Log.v("DEBUG_INFO","DEBUG_INFO:
Latitude: "+ String.valueOf(lat)+ " Longitude: "+
String.valueOf(lon));
}
else if ((l != null) && (isLocated == false)) {
lat = 0.0;
lon = 0.0;
} else {
lat = 0.0;
lon = 0.0;
}
} else {
new AlertDialog.Builder(NovaDenunciaActivity.this, R.style.AlertDialogCustom)
.setTitle("GPS TEXT!")
.setCancelable(false)
.setMessage("PLEASE SET GPS TEXT.")
.setPositiveButton("CLOSE",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
local.toggle();
}
} else {
isLocated = false;
}
}
});
}//onCreate
public void CheckGpsStatus(){
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("CHECKBOX","MARCADO");
}
} //Code end's
GPSTracker.java
[...]
public class GPSTracker extends Activity implements LocationListener {
Context context;
/*variables*/
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public GPSTracker(Context c) {
context = c;
}
/*variables*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} //Oncreate end's?
public Location getLocation() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Permission Text!\nPlease allow
permissions text.", Toast.LENGTH_LONG).show();
return null;
}
//Get the location manager
locationManager = (LocationManager)
context.getSystemService(context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
Log.v("DEBUG_INFO:", "Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
//longitudeField.setText("Location not available");
Log.v("DEBUG_INFO:", "Latitude: not available");
Log.v("DEBUG_INFO:", "Longitude: not available");
}
return location;
}
#Override
protected void onResume() {
super.onResume();
Log.v("DEBUG_INFO:", "REQUESTING LOCATION UPDATES");
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
Log.v("DEBUG_INFO:","STOP LOCATION UPDATES");
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
//latituteField.setText(String.valueOf(lat));
// longitudeField.setText(String.valueOf(lng));
Log.v("DEBUG_INFO:","Latitude: "+String.valueOf(lat));
Log.v("DEBUG_INFO:","Longitude: "+String.valueOf(lng));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(context, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(context, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
But when I click on checkbox the logcat (verbose) shows me the following:
V/DEBUG_INFO:: Latitude: not available
V/DEBUG_INFO:: Longitude: not available
The program should get latitude and longitude, if it does not exist it should call the locationManager.requestLocationUpdates(provider, 0, 0, this);
But I do not know what I'm doing wrong. Can someone help me?

Google Maps API shows location, but doesn't center

I'm working with the Google Maps API in Android Studio 2.2.3 and for some reason the location button works, but it doesn't center. Furthermore, I get a toast with the message that there no location was found.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getLocationPermission();
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionsGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful() && task.getResult() != null) {
Log.d(TAG, "onComplete: found location");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
} else {
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
Location currentLocation = (Location) task.getResult();
}
}
});
}
} catch (SecurityException e) {
}
}
The above code is what I to believe the code for finding the location, and then positioning the camera to that given location. I do not get any errors and when I set the LocationButton to true, and then click on it, it does center to my location.
By changing that code to
private void getDeviceLocation(){
try{
if(mLocationPermissionGranted){
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
Log.d(TAG, "onComplete: location found!");
Location currentLocation = (Location) task.getResult();
float currentZoom = mMap.getCameraPosition().zoom;//edit (added line)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLocation.getLatitude(),
currentLocation.getLongitude()), DEFAULT_ZOOM));//edit (changed line)
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
}
}
I managed so get a return with a location, after I manually set the location for the device because for some reason the location doesn't get determined rightaway.
For now the problem is solved!
Tried your code.
It didn't work for me but I solved the problem.
Here is the correct code.
private void getDeviceLocation(){
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionGranted){
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
Toast.makeText(DriverMapActivity.this, "Task is successful", Toast.LENGTH_SHORT).show();
Location currentLocation = (Location) task.getResult();
mLatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
moveCamera(mLatLng, DEFAULT_ZOOM);
}else{
Toast.makeText(DriverMapActivity.this, "Task is unsuccessful", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Toast.makeText(this, "SecurityException Found", Toast.LENGTH_SHORT).show();
}
}
So, if your app is crashing, you might wanna try this instead.

Loading screen upon doInBackground(String... params) and geocoder issues

I am trying to obtain location (Lat, Long, Address) via GPS/Cellular in my android application. This is the code below :
private class LocAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Obtaining location...Please Wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
LocationDSR locationDSR=new LocationDSR(getActivity());
locationDSR.getListAddressFromGeocoder();
return null;
}
#Override
protected void onPostExecute(String result) {
System.out.println("Location obtained");
dialog.hide();
}
}
And here is the locationDSR java :
public class LocationDSR implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
Context c;
GoogleApiClient mGoogleApiClient;
Location currentLocation;
SharedPreference sharedPreference;
ProgressDialog dialog;
public LocationDSR(Context c) {
this.c = c;
ApiClient();
mGoogleApiClient.connect();
}
synchronized void ApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(c)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
#Override
public void onLocationChanged(Location location) {
currentLocation = location;
System.out.println("onLocation changed :"+currentLocation);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
LocationRequest locationRequest = LocationRequest.create()
.setInterval(10 * 1000) // every 10 minutes
.setExpirationDuration(10 * 1000) // After 10 seconds
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, locationRequest, this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void getListAddressFromGeocoder() {
new AddressAsync().execute();
System.out.println("Inside getListAddressFromGeocoder");
}
class AddressAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
List<Address> addresses = null;
sharedPreference = new SharedPreference(c);
System.out.println("Inside doInBackground");
System.out.println("Current location : " + currentLocation);
if (currentLocation == null) {
LocationManager mlocManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
System.out.println("Current location null block");
try {
if (ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(c, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
currentLocation = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Obtraining from GPS");
System.out.println("GPSlocation : "+currentLocation);
// Check both providers even for lastKnownLocation
if (currentLocation == null) {
currentLocation = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("Obtaining from network provider");
}
} catch (Exception e) {
System.out.println("Insiode catch block for current location not obtained");
e.printStackTrace();
}
}
if (currentLocation != null) {
String complete_address;
final double latitude = currentLocation.getLatitude();
final double longitude = currentLocation.getLongitude();
System.out.println("LATITUDE: " + currentLocation.getLatitude());
System.out.println("LONGITUDE: " + currentLocation.getLongitude());
sharedPreference.saveLatLogAddressPref(String.valueOf(latitude), String.valueOf(latitude), "Not available", true);
//Storing the latitude and longitude in sharedPreference (To be used in case address is not obtained or geocoder timesout)
ConnectionDetector cd = new ConnectionDetector(c);
if (cd.isInternetOn()) {
System.out.println("Internet on detected");
Geocoder geocoder = new Geocoder(c);
try {
System.out.println("Latitude for address : "+latitude);
System.out.println("Longitude for address : "+longitude);
addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
Address addr = null;
if (addresses != null && addresses.size() > 0) {
addr = addresses.get(0);
String info = "Address is: ";
info += addr.getMaxAddressLineIndex() > 0 ? addr
.getAddressLine(0) : "";
info = info + ", " + addr.getLocality() + ", "
+ addr.getCountryName();
System.out.println("INFO : "+info);
} else
System.out.println("Address not found");
if (addresses != null || addresses.size() > 0) {
System.out.println("Addresses : "+addresses);
for (Address address : addresses) {
complete_address = String.valueOf(address.getAddressLine(0) + " " + address.getAddressLine(1) + " " + address.getAddressLine(2));
System.out.println("Complete address : "+complete_address);
if (complete_address.equals(" null null"))
{
complete_address = String.valueOf(address.getAdminArea()+" "+address.getLocality());
sharedPreference.saveLatLogAddressPref(String.valueOf(latitude), String.valueOf(latitude), complete_address, true);
}
else
{
sharedPreference.saveLatLogAddressPref(String.valueOf(latitude), String.valueOf(latitude), complete_address, true);
}
}
}
} catch (IOException e) {
System.out.println("Inside catch for geocoder");
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
}
}
The loading screen however pops up showing " Obtaining location...Please Wait..." but only for like 2 seconds. Within that time only the Latitude and Longitudes are obtained and not the Address. It takes about 2-3 seconds more for the address query addresses = geocoder.getFromLocation(currentLocation.getLatitude(), currentLocation.getLongitude(), 1); to get completed (as I can see it in the logcat). I am unable to understand how to keep the loading screen for the address query as well.
Also, sometimes during querying the address via gecoder, it shows
java.io.IOException: Timed out waiting for response from server
Any help is appreciated.

Categories

Resources