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
Related
Am trying to set up an app that would notify the user when his/her location is with in the polygon.
I have read about using polyutils library but have not been successful in implementing them.
Here is what i Tried
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
mMap.setMapType(mMap.MAP_TYPE_SATELLITE);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(48.146536, 16.291830)));
mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
DrawPolygon();
// Log.i(TAG, "onLocationChanged: location" + latLng);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this, null);
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
}
private void DrawPolygon() {
mPolygon1 = mMap.addPolygon(new PolygonOptions()
.strokeColor(COLOR_PURPLE_ARGB)
.add(
new LatLng(48.146536, 16.291830),
new LatLng(48.146772, 16.290146),
new LatLng(48.147397, 16.290380),
new LatLng(48.147177, 16.291970)));
// Store a data object with the polygon, used here to indicate an arbitrary type.
mPolygon1.setTag("alpha");
// Style the polygon.
// stylePolygon(polygon1);
mPolygon2 = mMap.addPolygon(new PolygonOptions()
.strokeColor(COLOR_BLUE_ARGB)
.add(
new LatLng(48.146491, 16.290989),
new LatLng(48.146265, 16.290898),
new LatLng(48.146171, 16.291819),
new LatLng(48.146359, 16.291870)));
mPolygon2.setTag("beta");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
for (Polygon polgon : getPolygons()) {
if (PolyUtil.containsLocation(latLng, polgon.getPoints(), true)) {
// found it open a info window
Log.i(LOG_TAG, "Your Currently in : " + polgon);
return;
}
}
}
public Collection<Polygon> getPolygons() {
Collection<Polygon> polygons = new ArrayList<Polygon>();
((ArrayList<Polygon>) polygons).add(1, mPolygon1);
((ArrayList<Polygon>) polygons).add(2, mPolygon2);
return polygons;
}
When i run the app the IDE throws an error pointing at the lines indexoutofBounds Exception and the app does not run.
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;
}
}
}
});
}
I've implemented the fused location api in my code. I can clearly see the changes of latitude and longitude for every required (Priority High accuracy,Interval- 1sec,fastest interval -1s) seconds in my logs. But the getSpeed() is always returning 0.0 in motoG (marshmallow). But the similar code works fine in Lenovo(marhsmallow).
While exploring this issue, articles stated difficulties in locking agps in motoG.But in my case lat and long update is fine which means locking is considerably good. :(
Tried different settings, nothing works. I need solution regarding this issue from someone who had overcome this. Thanks in advance.
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
ActivityCompat.OnRequestPermissionsResultCallback,
LocationListener {
private static final String TAG = "MainActivity";
private static final int REQUEST_LOCATION_PERMISSION = 1;
private boolean mPermissionApproved;
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPermissionApproved = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
if (!mPermissionApproved) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onPause() {
super.onPause();
if ((mGoogleApiClient != null) && (mGoogleApiClient.isConnected()) &&
(mGoogleApiClient.isConnecting())) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
public void onConnected(Bundle bundle) {
requestLocation();
}
private void requestLocation() {
if (mPermissionApproved) {
LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(0)
.setFastestInterval(0);
LocationServices.FusedLocationApi
.requestLocationUpdates(mGoogleApiClient, locationRequest, this)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.getStatus().isSuccess()) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Successfully requested location updates");
}
} else {
Log.e(TAG,
"Failed in requesting location updates, "
+ "status code: "
+ status.getStatusCode() + ", message: " + status
.getStatusMessage());
}
}
});
}
}
#Override
public void onConnectionSuspended(int i) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this,"latitude::" + location.getLatitude()+" longitude::"+ location.getLongitude()+ " Speed::" + location.getSpeed(), Toast.LENGTH_SHORT).show();
}
#Override
public void onRequestPermissionsResult( int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if ((grantResults.length == 1)
&& (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
mPermissionApproved = true;
if(mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
requestLocation();
}
} else {
mPermissionApproved = false;
}
}
}
}
For countless hours, I have been trying to get the user's current location upon launching my app, but then every approach I have tried has returned null.
My instantiation of the GoogleApiClient takes place in "onCreate"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
FirebaseMessagingHelper.registerDevice(this, FirebaseInstanceId.getInstance().getToken());
activity = this;
//xaxaxa
driverMapView = (MapView) findViewById(R.id.googleMapObject);
driverMapView.onCreate(savedInstanceState);
driverMapView.getMapAsync(this);
getUserToEnableCameraUsage();
if (googleApiClient == null)
{
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
googleApiClient.connect();
Here is the code in my project (extremely similar to the code provided in the api's tutorial:
#Override
public void onConnected(#Nullable Bundle bundle)
{
int LOCATION_ALLOWED = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (LOCATION_ALLOWED != PackageManager.PERMISSION_GRANTED)
{
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null)
{
driverGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 16));
testHelper.setDriverLatLngLocation(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()));
}
}
}
protected void createLocationRequest()
{
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(500);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
PendingResult<LocationSettingsResult> pendingResult = LocationServices
.SettingsApi
.checkLocationSettings(googleApiClient, locationSettingsRequestBuilder.build());
pendingResult.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(#NonNull LocationSettingsResult locationSettingsResult)
{
Status result = locationSettingsResult.getStatus();
if (result.getStatusCode() == LocationSettingsStatusCodes.SUCCESS)
{
requestingLocationUpdates = true;
startLocationUpdates();
Toast.makeText(MainActivity.this, "Gucci", Toast.LENGTH_SHORT).show();
}
if (result.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
{
requestingLocationUpdates = false;
Toast.makeText(MainActivity.this, "Please enable location services", Toast.LENGTH_SHORT).show();
}
if (result.getStatusCode() == LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE)
{
requestingLocationUpdates = false;
Toast.makeText(MainActivity.this, "App cannot access settings", Toast.LENGTH_SHORT).show();
}
}
});
}
protected void startLocationUpdates()
{
int LOCATION_ALLOWED = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (LOCATION_ALLOWED != PackageManager.PERMISSION_GRANTED)
{
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)
{
driverGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 16));
testHelper.setDriverLatLngLocation(new LatLng(location.getLatitude(), location.getLongitude()));
Toast.makeText(MainActivity.this, "It's working", Toast.LENGTH_SHORT).show();
}
protected void stopLocationUpdates()
{
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
requestingLocationUpdates = false;
}
I instantiate "createLocationRequest here:
public void onMapReady(GoogleMap googleMap)
{
//Setting map starts here
int LOCATION_ALLOWED = ContextCompat.checkSelfPermission(this.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (LOCATION_ALLOWED == PackageManager.PERMISSION_GRANTED)
{
googleMap.setMyLocationEnabled(true);
}
createLocationRequest();
The instantiation of "createLocationRequest()" takes place before the block of code that needs it and it is null?
I have looked over multiple solutions, but they've all not helped me. I was hoping that maybe someone could help me out as this has been really bothering me and has halted the development of my app.
I am a learner in android. I am trying to get weather on current location. There is a "Refresh" button in my app to update the UI with latest weather details. When the app loads, it shows weather of 0.0, 0.0 latitude and longitude. When I click on "Refresh" button, it shows the weather of my current location. How can I get the weather of my current location when the app loads? I have used Google Play Services to get the current location. Below is my code.
MainActivity.java
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
public String apiKey;
public double latitude;
public double longitude;
public String forecastUrl;
public static final String TAG = MainActivity.class.getSimpleName();
private GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
public MainActivity() {
apiKey = “XXXXXXXXXX";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buildGoogleApiClient();
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast();
}
});
getForecast();
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void getForecast() {
if (isNetworkAvailable()) {
forecastUrl = “http://www.forecastUrlGoesHere.com/" + apiKey + “/“ + latitude + "," + longitude;
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
if (response.isSuccessful()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
updateView(); //updates the screen ui
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_error_message), Toast.LENGTH_LONG).show();
}
}
private void updateView() {
//code to update ui
}
private boolean isNetworkAvailable() {
//check network availability
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
private void toggleRefresh() {
}
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, latitude + " " + longitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getString(R.string.no_location_detected), Toast.LENGTH_LONG).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, 9000);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Connection failed, ERROR: " + connectionResult.getErrorCode());
}
}
}
Well there are a few ways to get the expected result. Let me write the steps for one of them:
a) Use a ProgressDialog and start it in onCreate
b) Move the getForecast() from onCreate
c) In the onConnected method, once the lat and long are available, check if the ProgressDialog is still visible. If yes, dismiss this dialog and call getForecast
ProgressDialog link
http://developer.android.com/reference/android/app/ProgressDialog.html
In your onConnected callback, call getForecast();:
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
longitude = mLastLocation.getLongitude();
Toast.makeText(this, latitude + " " + longitude, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, getString(R.string.no_location_detected), Toast.LENGTH_LONG).show();
}
getForecast();
}