get current location with runOnUiThread - java

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

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

How to show my current location using mapbox SDK?

I'm trying to use the mapbox SDK to get my current location and set the navigation, but it's not working. I was trying to implement this code following the tutorial from the mapbox website.
public class pos extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
//private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaWhkaW5hIiwiYSI6ImNqaDRveHdhcjB1ZTIyd253M2R2MGhwY28ifQ.If9oJq_rILeuaK1sjp9-nw");
setContentView(R.layout.activity_pos);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
/* button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);*/
}
;
});
/*button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});*/
}
;
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Try modifying your methods with this:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
and your onStart with this:
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
locationEngine.addLocationEngineListener(this);
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}

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.

LocationClient requestUpdates onLocationChanged never called

I have this code which I use to position a map app. I tested it in a Galaxy S2 device and works fine, but when I tested it in a nexus 4 device the onLocationChanged callback never gets called. What could I be doing wrong?
Here is my activity code:
public class BaseMapActivity extends FragmentActivity implements Injectable,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private MapEntity component;
private boolean yetStarted = false;
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
private Location location;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
mLocationClient = new LocationClient(this, this, this);
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); // TODO
mLocationRequest.setInterval(5000); // TODO
mLocationRequest.setFastestInterval(5000); // TODO
replaceFragment(R.id.map_container, mapFragment);
// Agrega el fragment de extras
Fragment extrasFragment = component.getExtrasFragment();
replaceFragment(R.id.map_extras, extrasFragment);
}
#Override
protected void onStart() {
super.onStart();
mLocationClient.connect();
}
#Override
protected void onStop() {
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(this);
mLocationClient.disconnect();
}
super.onStop();
}
#Override
public void onConnected(Bundle arg0) {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
location = mLocationClient.getLastLocation();
if (location == null) {
return;
}
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
}
#Override
public void onDisconnected() {
mLocationClient.removeLocationUpdates(this);
Toast.makeText(this, "onDisconnected. Please re-connect.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
component.setCenter(location);
String msg = "Updated Location: "
+ Double.toString(location.getLatitude()) + ","
+ Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CONNECTION_FAILURE_RESOLUTION_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
break;
}
}
}
#SuppressLint("ShowToast")
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Toast.makeText(this, "An error ocurred getting current location",
Toast.LENGTH_SHORT);
}
}
}
Whats weird is that its working in one device but not in the other.
Try to set location mock up to see if the locationChange is called or not.
Here you have an example i was using for this before production.
private Location createMockLocation() {
if (mockLocation == null) {
mockLocation = new Location("mock");
mockLocation.setLatitude(41.4934133);
mockLocation.setLongitude(-23.8729252);
mockLocation.setAccuracy(1.0f);
mockLocation.setTime(new Date().getTime());
} else {
mockLocation.setLatitude(mockLocation.getLatitude() + 0.00003);
mockLocation.setLongitude(mockLocation.getLongitude() + 0.00001);
mockLocation.setTime(new Date().getTime());
}
return mockLocation;
}
private void mockLocation() {
LocationServices.FusedLocationApi.setMockMode(clientApi, true);
LocationServices.FusedLocationApi.setMockLocation(clientApi, createMockLocation());
final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
LocationServices.FusedLocationApi.setMockLocation(clientApi, createMockLocation());
// Log.d("MockLocation",
// "mockLocation: Lat:"+mockLocation.getLatitude()+" Long:"+mockLocation.getLongitude());
}
}, 0, NORMAL_INTERVAL, TimeUnit.MILLISECONDS);
}
With this method you get an update position each NORMAL_INTERVAL in ms.
Hope this helps :).

Categories

Resources