Remove updates on location manager not working - java

I have a map on which I want to show user's current location and I am calling an api after getting user's location to get the nearby merchants.
I am getting the user's current location, also all the merchants are getting plot by markers on map.
But I have called the setMap method in the onLocationChanged() method of LocationListener. This method get's called continuously.
I want to get the location once and show on the marker, again when next time user comes to this fragment then only I want to get updated location.
But now it's going in a loop continuously that onLocation method get's called and so accessMerchants is getting called.
To stop this I tried to remove updates from location manager, also I tried to set a boolean variable if it first time goes in onLocationChanged() method, it will be false but again it is also going in a loop.
Remove updates also not working, if remove updates is worked, then onLocationChanged method should not get called again right?
public class SearchMerchantFragment extends Fragment implements GetSearchedMerchantsAsyncTask.GetSearchedMerchantsCallBack, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search_merchant, container, false);
setUpUI(view);
return view;
}
public void setUpUI(View view) {
initializeLocationManager();
requestLocation();
setUpMapIfNeeded();
mLocationsList = new ArrayList<>();
markers = new ArrayList<>();
edtSearch = (EditText) view.findViewById(R.id.edtSearch);
rv_fetch_merchants = (RecyclerView) view.findViewById(R.id.rv_fetch_merchants);
merchantsList = new ArrayList<Merchants>();
merchantsAdapter = new SearchedMerchantsAdapter(this.getContext(), merchantsList);
rv_fetch_merchants.setLayoutManager(new LinearLayoutManager(getActivity()));
rv_fetch_merchants.setAdapter(merchantsAdapter);
rv_fetch_merchants.setHasFixedSize(true);
rv_fetch_merchants.setItemViewCacheSize(30);
rv_fetch_merchants.setDrawingCacheEnabled(true);
rv_fetch_merchants.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
//get searched merchants
public void accessMerchants() {
if (CommonUtils.isConnectedToInternet(getContext())) {
new GetSearchedMerchantsAsyncTask(getActivity(), SearchMerchantFragment.this).execute(access_token, sessionUserId, String.valueOf(mLastLocation.getLatitude()), String.valueOf(mLastLocation.getLongitude()));
} else {
showAlert(String.valueOf(R.string.check_network));
}
}
#Override
public void doPostExecute(ArrayList<Merchants> merchantsArrayList) {
merchantsList.clear();
merchantsList.addAll(merchantsArrayList);
merchantsAdapter.notifyDataSetChanged();
for (Merchants merchants : merchantsList) {
LatLng latLng = new LatLng(merchants.getLatitude(), merchants.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title(merchants.getKirana_name());
Marker m = mGoogleMap.addMarker(marker);
markers.add(m);
}
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
// getLocation();
}
}
//setup map
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
// Toast.makeText(getActivity(),"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
private void removeMarkers() {
if (mGoogleMap != null) {
for (Marker marker : markers) {
marker.remove();
}
mGoogleMap.clear();
markers.clear();
}
}
#Override
public void onDetach() {
super.onDetach();
mapConnected = false;
}
return true;
}
public void setMap() {
try {
int locationPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
int coarseLocation = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_COARSE_LOCATION);
if(locationPermission == PackageManager.PERMISSION_GRANTED && coarseLocation == PackageManager.PERMISSION_GRANTED && GPSTracker.isGPSEnabled) {
if(receivedLocation) {
receivedLocation = false;
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
accessMerchants();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLang);
markerOptions.title(getString(R.string.position));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mGoogleMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(mLatLang).zoom(14).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
// mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(5000); //5 seconds
// mLocationRequest.setFastestInterval(3000); //3 seconds
// mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
LocationListener locationListener = new LocationListener();
mLocationManager.removeUpdates(locationListener);
}
}
else {
showAlert(getString(R.string.locationAlert));
}
} catch (SecurityException e) {
}
}
private void initializeLocationManager() {
// Log.e(Application.TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
showAlert(getString(R.string.locationAlert));
}
}
public class LocationListener implements android.location.LocationListener {
public LocationListener() {
}
public LocationListener(String provider) {
Log.e(Application.TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(Application.TAG, "onLocationChanged: " + location);
receivedLocation = true;
mLastLocation.set(location);
if (receivedLocation) {
setMap();
}
}
#Override
public void onProviderDisabled(String provider) {
Log.e(Application.TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(Application.TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(Application.TAG, "onStatusChanged: " + provider);
}
}
public void requestLocation() {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
What's going wrong?? Please help.. Where should I call removeUpdates?? thank you..

You register for updates from 2 providers, did you deregister from both?
Also, to make the boolean flag work you need to make a change- set it to true at the end of the function, and change the if to if(!receivedLocation) That will make it run only once. As it is, it will never run.

Related

OnLocationChanged never called android studio LocationListener GoogleApiClient

I'm developing a taxi application. The only problem is my marker doesn't update it's location screamingly on mapview. After some debugging I noticed that the listener named onLocationChanged is never called!!!
The idea is to view a marker on mapview to view driver's location and track is own location while driver. But, the problem is his marker never changes!.
Here is my code:
public class HomeFragment extends FragmentManagePermission implements OnMapReadyCallback, DirectionCallback, Animation.AnimationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public String NETWORK;
public String ERROR = "حدث خطأ";
public String TRYAGAIN;
Boolean flag = false;
GoogleMap myMap;
ImageView current_location, clear;
MapView mMapView;
int i = 0;
String result = "";
Animation animFadeIn, animFadeOut;
String TAG = "home";
LinearLayout linear_request;
String permissionAsk[] = {
PermissionUtils.Manifest_CAMERA,
PermissionUtils.Manifest_WRITE_EXTERNAL_STORAGE,
PermissionUtils.Manifest_READ_EXTERNAL_STORAGE,
PermissionUtils.Manifest_ACCESS_FINE_LOCATION,
PermissionUtils.Manifest_ACCESS_COARSE_LOCATION
};
CardView rides, earnings;
private String driver_id = "";
private String cost = "";
private String unit = "";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private Double currentLatitude;
private Double currentLongitude;
private View rootView;
private String check = "";
private String drivername = "";
private Marker my_marker;
private boolean isShown = true;
private FusedLocationProviderClient fusedLocationProviderClient;
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fusedLocationProviderClient = new FusedLocationProviderClient(requireContext());
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
NETWORK = getString(R.string.network_not_available);
TRYAGAIN = getString(R.string.tryagian);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
rootView = inflater.inflate(R.layout.home_fragment, container, false);
// globatTitle = "Home";
((HomeActivity) getActivity()).fontToTitleBar(getString(R.string.home));
bindView(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
askCompactPermissions(permissionAsk, new PermissionResult() {
#Override
public void permissionGranted() {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
#Override
public void permissionDenied() {
}
#Override
public void permissionForeverDenied() {
openSettingsApp(getActivity());
}
});
} else {
if (!GPSEnable()) {
tunonGps();
} else {
getCurrentlOcation();
}
}
} catch (Exception e) {
Log.e("tag", "Inflate exception " + e.toString());
}
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1000) {
if (resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
getCurrentlOcation();
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
}
}
}
#Override
public void onPause() {
super.onPause();
try {
if (getActivity() != null && mMapView != null) {
mMapView.onPause();
}
if (mGoogleApiClient != null) {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
} catch (Exception e) {
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
if (mMapView != null) {
mMapView.onDestroy();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
if (mMapView != null) {
mMapView.onSaveInstanceState(outState);
}
} catch (Exception e) {
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
try {
if (mMapView != null) {
mMapView.onLowMemory();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
if (mMapView != null) {
mMapView.onStop();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
} catch (Exception e) {
}
}
#Override
public void onResume() {
super.onResume();
try {
if (mMapView != null) {
mMapView.onResume();
}
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
} catch (Exception e) {
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onMapReady(GoogleMap googleMap) {
myMap = googleMap;
myMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(final Marker marker) {
View v = null;
if (getActivity() != null) {
v = getActivity().getLayoutInflater().inflate(R.layout.view_custom_marker, null);
TextView title = (TextView) v.findViewById(R.id.t);
TextView t1 = (TextView) v.findViewById(R.id.t1);
TextView t2 = (TextView) v.findViewById(R.id.t2);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "font/AvenirLTStd_Medium.otf");
t1.setTypeface(font);
t2.setTypeface(font);
String name = marker.getTitle();
title.setText(name);
String info = marker.getSnippet();
t1.setText(info);
driver_id = (String) marker.getTag();
drivername = marker.getTitle();
}
return v;
}
});
if (myMap != null) {
tunonGps();
}
}
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
}
#Override
public void onDirectionFailure(Throwable t) {
}
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
public void bindView(Bundle savedInstanceState) {
MapsInitializer.initialize(this.getActivity());
mMapView = (MapView) rootView.findViewById(R.id.mapview);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
// load animations
animFadeIn = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_open);
animFadeOut = AnimationUtils.loadAnimation(getActivity(),
R.anim.dialogue_scale_anim_exit);
animFadeIn.setAnimationListener(this);
animFadeOut.setAnimationListener(this);
rides = (CardView) rootView.findViewById(R.id.cardview_totalride);
earnings = (CardView) rootView.findViewById(R.id.earnings);
Utils.overrideFonts(getActivity(), rootView);
getEarningInfo();
}
public void getEarningInfo() {
final ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
RequestParams params = new RequestParams();
if (Utils.haveNetworkConnection(getActivity())) {
params.put("driver_id", SessionManager.getUserId());
}
Server.setHeader(SessionManager.getKEY());
Server.get(Server.EARN, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("earn", response.toString());
try {
if (response.has("status") && response.getString("status").equalsIgnoreCase("success")) {
if (response.getJSONObject("data").getJSONObject("request").length() != 0) {
Gson gson = new Gson();
PendingRequestPojo pojo = gson.fromJson(response.getJSONObject("data").getJSONObject("request").toString(), PendingRequestPojo.class);
((HomeActivity) getActivity()).setPojo(pojo);
((HomeActivity) getActivity()).setStatus(pojo, "", false);
}
String today_earning = response.getJSONObject("data").getString("today_earning");
String week_earning = response.getJSONObject("data").getString("week_earning");
String total_earning = response.getJSONObject("data").getString("total_earning");
String total_rides = response.getJSONObject("data").getString("total_rides");
try {
String unit = response.getJSONObject("data").getString("unit");
//SessionManager.getInstance().setUnit(unit);
} catch (JSONException e) {
}
TextView textView_today = (TextView) rootView.findViewById(R.id.txt_todayearning);
TextView textView_week = (TextView) rootView.findViewById(R.id.txt_weekearning);
TextView textView_overall = (TextView) rootView.findViewById(R.id.txt_overallearning);
TextView textView_totalride = (TextView) rootView.findViewById(R.id.txt_total_ridecount);
textView_today.setText(today_earning);
textView_week.setText(week_earning);
textView_overall.setText(total_earning);
textView_totalride.setText(total_rides);
} else {
Toast.makeText(getActivity(), response.getString("data"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getActivity(), getString(R.string.error_occurred), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFinish() {
super.onFinish();
if (progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
#SuppressWarnings({"MissingPermission"})
#Override
public void onConnected(#Nullable Bundle bundle) {
try {
android.location.Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (myMap != null) {
myMap.clear();
my_marker = myMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Your are here."));
my_marker.showInfoWindow();
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
myMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (isShown) {
isShown = false;
rides.startAnimation(animFadeOut);
rides.setVisibility(View.GONE);
earnings.startAnimation(animFadeOut);
earnings.setVisibility(View.GONE);
} else {
isShown = true;
rides.setVisibility(View.VISIBLE);
rides.startAnimation(animFadeIn);
earnings.setVisibility(View.VISIBLE);
earnings.startAnimation(animFadeIn);
}
}
});
}
setCurrentLocation(currentLatitude, currentLongitude);
}
} catch (Exception e) {
}
}
public void setCurrentLocation(final Double lat, final Double log) {
try {
my_marker.setPosition(new LatLng(lat, log));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(currentLatitude, currentLongitude), 15);
myMap.animateCamera(cameraUpdate);
RequestParams par = new RequestParams();
Server.setHeader(SessionManager.getKEY());
par.put("user_id", SessionManager.getUserId());
par.add("latitude", String.valueOf(currentLatitude));
par.add("longitude", String.valueOf(currentLongitude));
Server.post(Server.UPDATE, par, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
}
});
} catch (Exception e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
#Override
public void onLocationChanged(android.location.Location location) {
if (location != null) {
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
if (!currentLatitude.equals(0.0) && !currentLongitude.equals(0.0)) {
setCurrentLocation(currentLatitude, currentLongitude);
} else {
Toast.makeText(getActivity(), getString(R.string.couldnt_get_location), Toast.LENGTH_LONG).show();
}
}
}
public void getCurrentlOcation() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
}
public void tunonGps() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(30 * 1000);
mLocationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
// **************************
builder.setAlwaysShow(true); // this is the key ingredient
// **************************
PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi
.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result
.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can
// initialize location
// requests here.
getCurrentlOcation();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be
// fixed by showing the user
// a dialog.
try {
// Show the dialog by calling
// startResolutionForResult(),
// and checkky the result in onActivityResult().
status.startResolutionForResult(getActivity(), 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have
// no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
public Boolean GPSEnable() {
GPSTracker gpsTracker = new GPSTracker(getActivity());
if (gpsTracker.canGetLocation()) {
return true;
} else {
return false;
}
}
}
What's the problem with my code?

when i try to run client.newCall(request).execute() the app crashes

I am trying to make a get http call, but every time the code gets to this line, it crashes:
`
Response response = client.newCall(request).execute()
`
My mainActivity is my MapsRestaurant and this is the code:
`
public class MapsRestaurant extends AppCompatActivity implements OnMapReadyCallback {
private FusedLocationProviderClient client;
GoogleMap mMap;
Conection conexao;
OkHttpClient clientHttp = new OkHttpClient();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps_restaurant);
client = LocationServices.getFusedLocationProviderClient(this);
conexao = new Conection();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
}
#SuppressLint("MissingPermission")
#Override
protected void onResume() {
super.onResume();
if (ContextCompat.checkSelfPermission(MapsRestaurant.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsRestaurant.this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(MapsRestaurant.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
ActivityCompat.requestPermissions(MapsRestaurant.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
client.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null){
Log.i("Teste", location.getLatitude()+" "+location.getLongitude());
LatLng currentLoc = new LatLng(location.getLatitude(),location.getLongitude());
mMap.addMarker(new MarkerOptions().position(currentLoc).title("Localização Atual"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLoc, 15));
}else{
Log.i("teste", "falhou");
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
long locationInterval = 15000;
LocationRequest locationRequest = LocationRequest.create()
.setInterval(15000)
.setPriority(Priority.PRIORITY_BALANCED_POWER_ACCURACY);
//LocationRequest.Builder locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, locationInterval);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addAllLocationRequests(Collections.singleton(locationRequest));
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(builder.build())
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.i("Teste", locationSettingsResponse.getLocationSettingsStates()
.isNetworkLocationPresent() + " ");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if(e instanceof ResolvableApiException){
try{
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MapsRestaurant.this, 10);
}catch (IntentSender.SendIntentException r){
}
}
}
});
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult locationResult) {
if(locationResult == null){
Log.i("Teste", "local is null");
return;
}
for(Location location : locationResult.getLocations()){
Log.i("Teste", location.getLatitude() + " ");
}
}
};
client.requestLocationUpdates(locationRequest, locationCallback, null);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
conexao.get("https://travel-advisor.p.rapidapi.com/locations/v2/auto-complete?query=eiffel%20tower&lang=en_US&units=km");
}catch (IOException e){
}
}
});
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
mMap.setMinZoomPreference(6.0f);
mMap.setMaxZoomPreference(20.0f);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
`
And the code of the class Connection is here:
public class Conection {
public static void get(String urlStr) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://travel-advisor.p.rapidapi.com/locations/v2/auto-complete?query=eiffel%20tower&lang=en_US&units=km")
.get()
.addHeader("X-RapidAPI-Key", "MyKey")
.addHeader("X-RapidAPI-Host", "travel-advisor.p.rapidapi.com")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
Log.i("Teste", responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
}
I am trying to return a list of restaurants from the latitude and longitude using the Travel Advise API, initially I would like to return a fixed latitude and longitude to start testing the api

Timer is not getting called on scheduled time

I want to track a location every 10 minutes and send it to server through TraceDelivery async task. For this I tried to use a service and timer to get the location every 10 minutes.
But when from another activity I call the service it works only once, i.e. once TraceDelivery api gets called but not again. For testing I have given just a second delay still its not getting called again.
Also if I check if mLatLang is null and then call the TraceDelivery it it did not get called at least once. But if location is null it gets crashed with a null pointer on mLatLang.
Service code :
public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{
private Handler handler;
private Timer timer;
private TimerTask timerTask;
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private LatLng mLatLang;
LocationManager mLocationManager = null;
boolean gps_enabled = false;
boolean network_enabled = false;
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.GPS_PROVIDER)
};
/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public LocationTrackerService() {
super("HelloIntentService");
}
/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(1000);
buildGoogleApiClient();
mGoogleApiClient.connect();
handler = new Handler();
initializeLocationManager();
requestLocation();
startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
intent.getStringExtra("api_key"));
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
public void startTimer(String dlId,String ptId,String urId,String add,String key) {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask(dlId, ptId, urId,key);
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 1000, 1000);//
}
public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
String.valueOf(mLatLang.longitude),"", key);
Log.e("timer","success");
}
});
}
};
}
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
.addConnectionCallbacks(LocationTrackerService.this)
.addOnConnectionFailedListener(LocationTrackerService.this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
private void initializeLocationManager() {
// Log.e(Application.TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
if(!CommonUtils.isGPSEnabled(getApplicationContext()))
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
public class LocationListener implements android.location.LocationListener {
public LocationListener() {
}
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
//get current location
if(mLastLocation != null && !mLastLocation.equals("")) {
mLastLocation.set(location);
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
else {
}
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
//request for location, first by network, then by gps
public void requestLocation() {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
How can I achieve this?
Please help with this.Thank you..
IntentService will stop immediately one its finished the task in OnHandleIntent,
So instead of using IntentService try to use Service for long running operations.
The Android AlarmManager class can trigger an intent to be sent to your application at set intervals and execute the defined task.Probably what have you been looking for

Showing some number on snackbar when I am getting location from Location listener

I am using a map and location listener. I am calling the location listener when the map is ready and showing marker's on map after getting the location from location listener , all this in setMap() method.
When I am getting the location I see some numbers on snackbar, I dont know from where it is coming, nowhere I am showing it. I am showing snackbar's to show the internet and gps alert. But this is coming from nowhere.
Looks like this:
What is it??
Code:
public class SearchMerchantFragment extends Fragment implements GetSearchedMerchantsAsyncTask.GetSearchedMerchantsCallBack, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.GPS_PROVIDER)
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search_merchant, container, false);
setUpUI(view);
return view;
}
public void setUpUI(View view) {
setUpMapIfNeeded();
sessionData = new SessionData(getActivity());
sessionUserId = sessionData.getString("user_id", "-1");
access_token = sessionData.getString("api_key", "-1");
mLocationsList = new ArrayList<>();
markers = new ArrayList<>();
edtSearch = (EditText) view.findViewById(R.id.edtSearch);
parentLayout = (RelativeLayout) view.findViewById(R.id.parentLayout);
rv_fetch_merchants = (RecyclerView) view.findViewById(R.id.rv_fetch_merchants);
merchantsList = new ArrayList<Merchants>();
merchantsAdapter = new SearchedMerchantsAdapter(this.getContext(), merchantsList);
rv_fetch_merchants.setLayoutManager(new LinearLayoutManager(getActivity()));
rv_fetch_merchants.setAdapter(merchantsAdapter);
rv_fetch_merchants.setHasFixedSize(true);
rv_fetch_merchants.setItemViewCacheSize(30);
rv_fetch_merchants.setDrawingCacheEnabled(true);
rv_fetch_merchants.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
}
//get searched merchants
public void accessMerchants() {
new GetSearchedMerchantsAsyncTask(getActivity(), SearchMerchantFragment.this).execute(access_token, sessionUserId, String.valueOf(mLastLocation.getLatitude()), String.valueOf(mLastLocation.getLongitude()));
}
#Override
public void doPostExecute(ArrayList<Merchants> merchantsArrayList) {
merchantsList.clear();
merchantsList.addAll(merchantsArrayList);
merchantsAdapter.notifyDataSetChanged();
for (Merchants merchants : merchantsList) {
LatLng latLng = new LatLng(merchants.getLatitude(), merchants.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)).title(merchants.getKirana_name());
Marker m = mGoogleMap.addMarker(marker);
markers.add(m);
}
}
public void showAlert(String alert) {
Snackbar snackbar = Snackbar.make(parentLayout, alert, Snackbar.LENGTH_LONG);
snackbar.show(); // Don’t forget to show!
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getMapAsync(this);
}
}
//setup map
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
buildGoogleApiClient();
mGoogleApiClient.connect();
mapConnected = true;
if (mapConnected) {
if (CommonUtils.isConnectedToInternet(getActivity())) {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
initializeLocationManager();
requestLocation();
}
else {
((HomeActivity) getActivity()).showAlert(getResources().getString(R.string.locationAlert));
}
} else {
((HomeActivity) getActivity()).showAlert(getResources().getString(R.string.check_network));
}
}
}
protected synchronized void buildGoogleApiClient() {
// Toast.makeText(getActivity(),"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onDetach() {
super.onDetach();
mapConnected = false;
mGoogleMap = null;
View view = getActivity().getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public void setMap() {
try {
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
accessMerchants();
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mLatLang);
markerOptions.title(getResources().getString(R.string.position));
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));
mMarker = mGoogleMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(mLatLang).zoom(14).build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
mLocationManager.removeUpdates(mLocationListeners[0]);
mLocationManager.removeUpdates(mLocationListeners[1]);
} catch (SecurityException e) {
}
}
private void initializeLocationManager() {
if (mLocationManager == null) {
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
}
boolean gps_enabled = false;
boolean network_enabled = false;
try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
// notify user
((HomeActivity) getActivity()).showAlert(getResources().getString(R.string.locationAlert));
}
}
public class LocationListener implements android.location.LocationListener {
public LocationListener() {
}
public LocationListener(String provider) {
Log.e(Application.TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(Application.TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
if(mapConnected)
setMap();
}
#Override
public void onProviderDisabled(String provider) {
Log.e(Application.TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(Application.TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(Application.TAG, "onStatusChanged: " + provider);
}
}
public void requestLocation() {
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(Application.TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(Application.TAG, "gps provider does not exist " + ex.getMessage());
}
}
}
As I did debug I found that I get this in onLocationChanged method when the setMap() method is called, before or after the method is called.
Which number is this?? Please help thank you..
Replace this in your code:
getString(R.string.locationAlert);
With this.
getResources().getString(R.string.locationAlert);
The issue is getString(R.string.locationAlert); this code returns the R file integer assigned space.

get current location with runOnUiThread

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();
}

Categories

Resources