getting null value for GoogleApiclient in fragment? - java

Here is my code. I am getting null in googleapiclient.
public class MapsActivity extends Fragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener, AdapterView.OnItemClickListener, DriverListner {
View view;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static String TAG = "MAP LOCATION";
Context mContext;
TextView mLocationMarkerText;
private LatLng mCenterLatLong;
private AddressResultReceiver mResultReceiver;
protected String mAddressOutput;
protected String mAreaOutput;
protected String mCityOutput;
protected String mStateOutput;
EditText mLocationAddress;
TextView mLocationText;
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
AutoCompleteTextView edtDropLocation;
LatLng source;
LatLng destination;
LinearLayout lytBottomView;
private List < DriverDetail > driverDetailsList = new ArrayList < > ();
DriverListAdapter driverListAdapter;
RecyclerView rv_driver_truck;
DriverDetail driverDetail;
Button book;
int driverId = 0, userId = 0;
String currentLocation = "", dropLocation = "", currentLat = "", currentLong = "", dropLat = "", dropLong = "", token = "",
vehicleId = "", bookingDateTime = "", truckRent = "";
private LocationRequest mLocationRequest;
Date currentTime;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_maps, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
userId = Integer.parseInt(TruckApplication.ReadStringPreferences(SharedPrefData.PREF_UserId));
token = TruckApplication.ReadStringPreferences(SharedPrefData.PREF_TOKEN);
currentTime = Calendar.getInstance().getTime();
Log.e("##dateandtime", String.valueOf(currentTime));
mLocationMarkerText = view.findViewById(R.id.locationMarkertext);
rv_driver_truck = view.findViewById(R.id.rv_driver_truck);
mLocationAddress = view.findViewById(R.id.Address);
mLocationText = view.findViewById(R.id.Locality);
edtDropLocation = view.findViewById(R.id.edtDropLocation);
lytBottomView = view.findViewById(R.id.lytBottomView);
book = view.findViewById(R.id.book);
edtDropLocation.setAdapter(new MapFragment.GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item_text));
edtDropLocation.setOnItemClickListener(this);
mLocationText.setOnClickListener(view - > openAutocompleteActivity());
mapFragment.getMapAsync(this);
if (checkPlayServices()) {
if (!AppUtils.isLocationEnabled(getContext())) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setMessage("Location not enabled!");
dialog.setPositiveButton("Open location settings", (paramDialogInterface, paramInt) - > {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
});
dialog.setNegativeButton("Cancel", (paramDialogInterface, paramInt) - > {});
dialog.show();
}
buildGoogleApiClient();
} else {
Toast.makeText(mContext, "Location not supported in this device", Toast.LENGTH_SHORT).show();
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
rv_driver_truck.setLayoutManager(linearLayoutManager);
rv_driver_truck.setItemAnimator(new DefaultItemAnimator());
getDriverList();
book.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBookRequest();
}
});
mResultReceiver = new AddressResultReceiver(new Handler());
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraChangeListener(cameraPosition - > {
Log.d("##Camera postion change" + "", cameraPosition + "");
mCenterLatLong = cameraPosition.target;
mMap.clear();
try {
Location mLocation = new Location("");
mLocation.setLatitude(mCenterLatLong.latitude);
mLocation.setLongitude(mCenterLatLong.longitude);
currentLat = String.valueOf(mCenterLatLong.latitude);
currentLong = String.valueOf(mCenterLatLong.longitude);
startIntentService(mLocation);
mLocationMarkerText.setText(getCompleteAddressString(mLocation.getLatitude(), mLocation.getLongitude()));
} catch (Exception e) {
e.printStackTrace();
}
});
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
changeMap(mLastLocation);
Log.d(TAG, "ON connected");
} else
try {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
try {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
try {
if (location != null)
changeMap(location);
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
#Override
public void onStart() {
super.onStart();
try {
mGoogleApiClient.connect();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStop() {
super.onStop();
try {
} catch (RuntimeException e) {
e.printStackTrace();
}
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {}
return false;
}
return true;
}
private void changeMap(Location location) {
Log.d(TAG, "Reaching map" + mMap);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (mMap != null) {
mMap.getUiSettings().setZoomControlsEnabled(false);
LatLng latLong;
latLong = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(10 f).tilt(50).build();
mMap.setMyLocationEnabled(true);
/* mMap.getUiSettings().setMyLocationButtonEnabled(true);*/
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// mLocationMarkerText.setText("Lat : " + location.getLatitude() + "," + "Long : " + location.getLongitude());
getCompleteAddressString(location.getLatitude(), location.getLongitude());
mLocationMarkerText.setText(getCompleteAddressString(location.getLatitude(), location.getLongitude()));
startIntentService(location);
} else {
Toast.makeText(getContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
String str = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
LatLng lastLocation = source;
edtDropLocation.setText(str);
dropLocation = str;
Geocoder coder = new Geocoder(getContext());
try {
ArrayList < Address > adresses = (ArrayList < Address > ) coder.getFromLocationName(str, 50);
for (Address add: adresses) {
double longitude = add.getLongitude();
double latitude = add.getLatitude();
dropLat = String.valueOf(latitude);
dropLong = String.valueOf(longitude);
destination = new LatLng(latitude, longitude);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(destination);
mMap.clear();
markerOptions.title(str);
markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.droppoint));
mMap.animateCamera(CameraUpdateFactory.newLatLng(destination));
mMap.addMarker(markerOptions);
getDriverList();
lytBottomView.setVisibility(View.VISIBLE);
driverListAdapter = new DriverListAdapter(getActivity(), driverDetailsList, this);
rv_driver_truck.setAdapter(driverListAdapter);
/* new GetPathFromLocation(lastLocation, destination, new DirectionPointListener() {
#Override
public void onPath(PolylineOptions polyLine) {
mMap.addPolyline(polyLine);
lytBottomView.setVisibility(View.VISIBLE);
}
}).execute();*/
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public DriverDetail driverDetail(DriverDetail driverDetail1) {
driverDetail = driverDetail1;
driverId = driverDetail1.getId();
truckRent = driverDetail1.getVehicleRent();
// Log.e("##DriverId", truckRent);
return driverDetail;
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
mAddressOutput = resultData.getString(AppUtils.LocationConstants.RESULT_DATA_KEY);
mAreaOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_AREA);
mCityOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_CITY);
mStateOutput = resultData.getString(AppUtils.LocationConstants.LOCATION_DATA_STREET);
displayAddressOutput();
if (resultCode == AppUtils.LocationConstants.SUCCESS_RESULT) {
}
}
}
protected void displayAddressOutput() {
try {
if (mAreaOutput != null)
mLocationAddress.setText(mAddressOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void startIntentService(Location mLocation) {
Intent intent = new Intent(getContext(), FetchAddressIntentService.class);
intent.putExtra(AppUtils.LocationConstants.RECEIVER, mResultReceiver);
intent.putExtra(AppUtils.LocationConstants.LOCATION_DATA_EXTRA, mLocation);
getActivity().startService(intent);
}
private void openAutocompleteActivity() {
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.build(getActivity());
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
} catch (GooglePlayServicesRepairableException e) {
GoogleApiAvailability.getInstance().getErrorDialog(getActivity(), e.getConnectionStatusCode(),
0 /* requestCode */ ).show();
} catch (GooglePlayServicesNotAvailableException e) {
String message = "Google Play Services is not available: " +
GoogleApiAvailability.getInstance().getErrorString(e.errorCode);
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(mContext, data);
LatLng latLong;
latLong = place.getLatLng();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLong).zoom(19 f).tilt(70).build();
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(mContext, data);
} else if (resultCode == RESULT_CANCELED) {
}
}
#SuppressLint("LongLogTag")
private String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
String strAdd = "";
Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
try {
List < Address > addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if (addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
strAdd = strReturnedAddress.toString();
currentLocation = strAdd;
Log.e("My Current loction address", strReturnedAddress.toString());
} else {
Log.w("My Current loction address", "No Address returned!");
}
} catch (Exception e) {
e.printStackTrace();
Log.w("My Current loction address", "Canont get Address!");
}
return strAdd;
}
private void getDriverList() {
ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
Call < OnlineDriverList > call = apiInterface.getDriverList();
call.enqueue(new Callback < OnlineDriverList > () {
#Override
public void onResponse(#NonNull Call < OnlineDriverList > call, Response < OnlineDriverList > response) {
// refreshLayout.setRefreshing(false);
if (response.isSuccessful()) {
OnlineDriverList onlineDriverList = response.body();
if (onlineDriverList.getDriverDetails().size() == 0) {
Toast.makeText(getContext(), "No Driver is Available at current Time ", Toast.LENGTH_SHORT).show();
} else {
driverDetailsList = onlineDriverList.getDriverDetails();
TruckBo.getInstance().setDriverArrayList(driverDetailsList);
// driverListAdapter.setData(driverDetailsList);
// refreshLayout.setVisibility(View.VISIBLE);
}
}
}
#Override
public void onFailure(Call < OnlineDriverList > call, Throwable t) {
//refreshLayout.setRefreshing(false);
Log.d("Error", t.getLocalizedMessage());
}
});
}
public void sendBookRequest() {
ApiInterface apiInterface = RetrofitManager.getInstance().create(ApiInterface.class);
Call < UserRegistration > call = apiInterface.booking(driverId, userId, truckRent, currentLocation, dropLocation,
currentLat, currentLong, dropLat, dropLong, token, "", ""
);
call.enqueue(new Callback < UserRegistration > () {
#Override
public void onResponse(Call < UserRegistration > call, Response < UserRegistration > response) {
if (response.isSuccessful()) {
Toast.makeText(getContext(), "Wait For Respond From Driver Side", Toast.LENGTH_SHORT).show();
lytBottomView.setVisibility(View.GONE);
} else {}
}
#Override
public void onFailure(Call < UserRegistration > call, Throwable t) {
Log.e("Error", t.getLocalizedMessage());
}
});
}
}
I am getting null here:
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
}
The first time it is not going to the current location and I am getting null googleapiclient, and on move marker, I am fetching address in starting I am not getting current location.

Related

GPS, Locate the first time, but not the second

I am trying to locate the user's location once, so I am using the merged location provider. The problem I have is that when I use it for the first time I locate the location but then if I turn off the GPS and press the text to locate again, it does not locate me again. What could be the problem that makes it work the first time? Many thanks.
public class DatosUbicacion extends Fragment {
private TextView tvLocalizar;
private FusedLocationProviderClient proveedor;
private LocationManager locationManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View vista = inflater.inflate(R.layout.fragment_ubicacion, container, false);
ids(vista);
locationManager=()requireActivity().getSystemService(Context.Location_Service);
proveedor = LocationServices.getFusedLocationProviderClient(getActivity());
tvLocalizar.setOnClickListener(v -> permiso);
return vista;
private void permiso() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
obtenerUbicacion();
} else if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
dialogo();
} else if (!shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
dialogoConfiguracion();
} else {
dialogo();
}
} else {
obtenerUbicacion();
}
}
#SuppressLint("MissingPermission")
public void obtenerUbicacion() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(1000);
locationRequest.setWaitForAccurateLocation(true);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
proveedor.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
Log.d("UBICACION", location.getLatitude() + "" + location.getLongitude());
} else {
proveedor.requestLocationUpdates(locationRequest, miUbicacionCallback, Looper.myLooper());
}
}).addOnFailureListener(e -> {
Toast.makeText(requireContext(), "error" + e.getMessage(), Toast.LENGTH_SHORT).show();
});
} else {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> tarea = LocationServices.getSettingsClient(requireContext()).checkLocationSettings(builder.build());
tarea.addOnFailureListener(e -> {
if (e instanceof ResolvableApiException) {
try {
IntentSenderRequest intentSenderRequest = new IntentSenderRequest.Builder(((ResolvableApiException) e).getResolution()).build();
contratoGps.launch(intentSenderRequest);
} catch (Throwable trowable) {
Log.e("gps", trowable.getMessage());
}
}
});
}
}
private LocationCallback miUbicacionCallback = new LocationCallback() {
#Override
public void onLocationResult(#NonNull LocationResult resultado) {
if (resultado == null) {
return;
}
Log.d("UBICACION", resultado.getLastLocation().getLatitude() + “ ” + resultado.getLastLocation().getLongitude());
};
private void dialogo(){
Dialog dialog = new Dialog(requireContext(), R.style.Theme_AppCompat_Light_Dialog_Alert);
dialog.setContentView(R.layout.dialog_camara);
Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
Button btnOk = dialog.findViewById(R.id.btn_ok);
Button btnCancelar = dialog.findViewById(R.id.btn_cancelar);
TextView permiso = dialog.findViewById(R.id.tv_permiso);
dialog.show();
btnOk.setOnClickListener(v -> {
this.contratoUbicacion.launch(Manifest.permission.ACCESS_FINE_LOCATION);
dialog.dismiss();
});
btnCancelar.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
}
private void dialogoConfiguracion() {
Dialog dialog = new Dialog(requireContext(), R.style.Theme_AppCompat_Light_Dialog_Alert);
dialog.setContentView(R.layout.dialog_ubicacion);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
Button ok = dialog.findViewById(R.id.btn_ok);
Button cancel = dialog.findViewById(R.id.btn_cancelar);
TextView permiso = dialog.findViewById(R.id.tv_permiso);
dialog.show();
ok.setOnClickListener(v -> {
configuracion();
});
cancel.setOnClickListener(v -> dialog.dismiss());
dialog.setCancelable(false);
}
private void configuracion() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", requireActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
ActivityResultLauncher<String> contratoUbicacion = registerForActivityResult(new ActivityResultContracts.RequestPermission(), resultado -> {
if (resultado) {
obtenerUbicacion();
} else {
Toast.makeText(requireContext(), "se necesitan permisos de ubicacion", Toast.LENGTH_SHORT).show();
}
});
ActivityResultLauncher<IntentSenderRequest> contratoGps = registerForActivityResult(new ActivityResultContracts.StartIntentSenderForResult(), resultado -> {
if (result.getResultCode() == Activity.RESULT_OK) {
obtenerUbicacion();
}
});
private void ids(View vista){
tvLocalizar = vista.findViewById(R.id.tv_localizar);
}
}
Xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/cl_ubicacion"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#color/plataforma"
tools:context=".preusuario.registro2.DatosUbicacion">
<TextView
android:id="#+id/tv_localizar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Obtener mi ubicacion actual"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Well, you have checked GPS_PROVIDER but you also need to check LocationManager.NETWORK_PROVIDER. So, you can get location status via Network when GPS is Off.
First of all, you need to check the permmissions and, also request the new permmissions if not granted.
// method to check
// if location is enabled
public boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
// method to request for permissions
public void requestPermissions() {
ActivityCompat.requestPermissions(FutureClientsMeet.this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_ID);
}
In your obtenerUbicacion() use something like below:
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// check if location is enabled
if (isLocationEnabled()) {
locationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
CurrentLat = String.valueOf(location.getLatitude());
CurrentLng = String.valueOf(location.getLongitude());
}
}
});
} else {
Toast.makeText(getApplicationContext(), "Please turn on" + " your location...", Toast.LENGTH_LONG).show();
}
} else {
requestPermissions();
}
Then, add requestNewLocationData() and LocationCallback to update the new location.
public LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
if (mLastLocation != null) {
//here you can get new location
Lat = mLastLocation.getLatitude();
Lng = mLastLocation.getLongitude();
}
}
};
#SuppressLint("MissingPermission")
public void requestNewLocationData() {
// Initializing LocationRequest
// object with appropriate methods
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
// setting LocationRequest
// on FusedLocationClient
locationProviderClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
locationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}

Getting results of nearby places from the current Location using Google Maps API

Here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
LocationListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
GoogleMap mMap;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
GoogleApiClient client;
Location mLastLocation;
Marker mCurrLocationMarker;
LatLng latLongCurrent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getSupportActionBar().setTitle("Map location");
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void findRestaurant(View view) {
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location=" + latLongCurrent.latitude + "," + latLongCurrent.longitude); //error attempt to read from field 'double...on a null object reference
stringBuilder.append("&radius=" + 1000);
stringBuilder.append("&keyword=" + "restaurant");
stringBuilder.append("&key=" + getResources().getString(R.string.google_places_key));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
NearbySearch nearbySearch = new NearbySearch(this);
nearbySearch.execute(dataTransfer);
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.map_options, menu);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Initializing the Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
client = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
client.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, mLocationRequest, this);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Change the map type based on the user's selection.
switch (item.getItemId()) {
case R.id.normal_map:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
return true;
case R.id.hybrid_map:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
return true;
case R.id.satellite_map:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
return true;
case R.id.terrain_map:
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("My current Position");
mCurrLocationMarker = mMap.addMarker(markerOptions);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(MapsActivity.this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept this to use the location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
}).create().show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (client == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Permission is denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private void moveCamera(LatLng latLang, float zoom, String title) {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLang, zoom));
//writing the code to drop the pin or marker
MarkerOptions options = new MarkerOptions().position(latLang).title(title);
mMap.addMarker(options);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
and this is my class NearbySearch.java code below:
public class NearbySearch extends AsyncTask<Object, String, String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
public NearbySearch(MapsActivity mapsActivity) {
}
#Override
protected String doInBackground(Object... objects) {
//requesting for the response from the google places API
mMap = (GoogleMap) objects[0];
try {
URL myUrl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myUrl.openConnection();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line);
}
//Receiving the data from json
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultArray = parentObject.getJSONArray("results");
for (int i = 0; i < resultArray.length(); i++) {
JSONObject jsonObject = resultArray.getJSONObject(i);
JSONObject locationObject = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = jsonObject.getString("lat");
String longitude = jsonObject.getString("lng");
JSONObject nameObject = resultArray.getJSONObject(i);
String nameRestaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.title(vicinity);
markerOptions.position(latLng);
mMap.addMarker(markerOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
I'm successfully fetching the user's current location but cannot find the solution to find the nearby restaurants from the current location. Please help to get rid of it as I'm stuck for 2 days here. Kindly tell me if any other solution is there too. Thanks!

mMap is null when trying to create a new marker

so, after a year or two i started this project again... by the time it was outdated it worked fine... but since android x came out i wanted to upgrade my application and got stuck on a error i find it funny...
quick brief, i have button that makes me online / offline.. on pressing the button the map should zoom at my curr. location and add a marker.. but here comes the error :
Logcat:
Process: com.app.mk.transport, PID: 22142
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
at com.app.mk.transport.DriverHome$16$1$1.onComplete(DriverHome.java:1110)
at com.firebase.geofire.GeoFire$2.onComplete(GeoFire.java:178)
at com.google.firebase.database.core.Repo$6.run(com.google.firebase:firebase-database##19.2.0:404)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
DriverHome.java ( Not The whole code ):
private void setUpAutocomplete() {
AutocompleteSupportFragment autocompleteFragment = new AutocompleteSupportFragment();
// final AutocompleteSupportFragment autocompleteFragment;
// autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
autocompleteFragment.setCountry("MK");
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), getResources().getString(R.string.google_open_api));
}
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ADDRESS));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
if (location_switch.isChecked()) {
destination = place.getAddress();
destination = destination.replace(" ", "+");
if (destination.contains("+(FYROM)")) {
destination = destination.replace("+(FYROM)", "");
}
mMap.clear();
getDirection();
}
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(DriverHome.this, "" + status.toString(), Toast.LENGTH_SHORT).show();
Log.i("MITKASIN", "An error occurred: " + status);
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.driver_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_trip_history) {
// Handle the camera action
} else if (id == R.id.nav_way_bill) {
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_update_Info) {
showDialogUpdateInfo();
} else if (id == R.id.nav_sign_out) {
signOut();
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showDialogUpdateInfo() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(DriverHome.this);
alertDialog.setTitle("Update Information");
alertDialog.setMessage("Please fill in the informations");
LayoutInflater inflater = this.getLayoutInflater();
View dialog_change_pwd = inflater.inflate(R.layout.layout_update_information, null);
final TextInputEditText edt_Name = dialog_change_pwd.findViewById(R.id.edtName);
final TextInputEditText edt_Phone = dialog_change_pwd.findViewById(R.id.edtPhone);
final ImageView image_upload = (ImageView) dialog_change_pwd.findViewById(R.id.image_upload);
image_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chooseImage();
}
});
alertDialog.setView(dialog_change_pwd);
alertDialog.setPositiveButton("UPDATE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
final android.app.AlertDialog waitingDialog = new SpotsDialog.Builder()
.setContext(DriverHome.this)
.setTheme(R.style.Orange)
.setMessage(R.string.waitingDialog_title)
.setCancelable(false)
.build();
waitingDialog.show();
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
String name = edt_Name.getText().toString();
String phone = edt_Phone.getText().toString();
Map<String, Object> updateInfo = new HashMap<>();
if (!TextUtils.isEmpty(name))
updateInfo.put("name", name);
if (!TextUtils.isEmpty(phone))
updateInfo.put("phone", phone);
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(updateInfo)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
waitingDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Information updated!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Information update Failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), Common.PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Common.PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri saveUri = data.getData();
if (saveUri != null) {
final ProgressDialog mDialog = new ProgressDialog(this);
mDialog.setMessage("Uploading...");
mDialog.show();
String imageName = UUID.randomUUID().toString();
final StorageReference imageFolder = storageReference.child("images/" + imageName);
imageFolder.putFile(saveUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mDialog.dismiss();
Toast.makeText(DriverHome.this, "Uploaded !", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(final Uri uri) {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
Map<String, Object> avatarUpdate = new HashMap<>();
avatarUpdate.put("avatarUrl", uri.toString());
DatabaseReference driverInformations = FirebaseDatabase.getInstance().getReference(Common.user_driver_tbl);
driverInformations.child(account.getId())
.updateChildren(avatarUpdate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(DriverHome.this, "Uploaded!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DriverHome.this, "Upload error !", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mDialog.setMessage("Upliaded " + progress + "%");
}
});
}
}
}
private void signOut() {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
else
builder = new AlertDialog.Builder(this);
builder.setMessage("Do you want to logout?")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Paper.init(this);
AccountKit.logOut();
Intent intent = new Intent(DriverHome.this, MainActivity.class);
startActivity(intent);
finish();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
private float getBearing(LatLng startPosition, LatLng endPosition) {
double lat = Math.abs(startPosition.latitude - endPosition.latitude);
double lng = Math.abs(startPosition.longitude - endPosition.longitude);
if (startPosition.latitude < endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)));
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude < endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 90);
else if (startPosition.latitude >= endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) (Math.toDegrees(Math.atan(lng / lat)) + 180);
else if (startPosition.latitude < endPosition.latitude && startPosition.longitude >= endPosition.longitude)
return (float) ((90 - Math.toDegrees(Math.atan(lng / lat))) + 270);
return -1;
}
private void updateFirebaseToken() {
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference tokens = db.getReference(Common.token_tbl);
Token token = new Token(FirebaseInstanceId.getInstance().getToken());
tokens.child(account.getId())
.setValue(token);
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
private void getDirection() {
currentPosition = new LatLng(Common.mLastLocation.getLatitude(), Common.mLastLocation.getLongitude());
String requestApi = null;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_reference=less_driving&" +
"origin=" + currentPosition.latitude + "," + currentPosition.longitude + "&" +
"destination=" + destination + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.i("MITKASIN", requestApi);
mServices.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
if (!polyLineList.isEmpty()) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 1);
mMap.animateCamera(mCameraUpdate);
// mMap.getUiSettings().setAllGesturesEnabled(true);
}
polylineOptiuons = new PolylineOptions();
polylineOptiuons.color(Color.GRAY);
polylineOptiuons.width(5);
polylineOptiuons.startCap(new SquareCap());
polylineOptiuons.endCap(new SquareCap());
polylineOptiuons.jointType(JointType.ROUND);
polylineOptiuons.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptiuons);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(7);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
if (!polyLineList.isEmpty()) {
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
}
//Animation
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions()
.position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.car)));
handler = new Handler();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 2000);
// mMap.getUiSettings().setScrollGesturesEnabled(true);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(DriverHome.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
// mMap.getUiSettings().setScrollGesturesEnabled(true);
}
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PEMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
buildLocationCallback();
buildLocationRequest();
if (location_switch.isChecked())
displayLocation();
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Request runtime permission
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, MY_PEMISSION_REQUEST_CODE);
} else {
buildLocationRequest();
buildLocationCallback();
if (location_switch.isChecked())
displayLocation();
}
}
private void buildLocationCallback() {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Common.mLastLocation = location;
}
displayLocation();
}
};
}
private void buildLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
Common.mLastLocation = location;
if (Common.mLastLocation != null) {
if (location_switch.isChecked()) {
final double latitude = Common.mLastLocation.getLatitude();
final double longitude = Common.mLastLocation.getLongitude();
//Update to Firebase
AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
#Override
public void onSuccess(Account account) {
geoFire.setLocation(account.getId(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (mCurrent != null) {
mCurrent.remove();
}
mCurrent = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Your Location"));
// Move camera to this position when set to online!
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 14.5f));
// Draw animation rotate marker
// rotateMarker(mCurrent, 360, mMap);
}
});
}
#Override
public void onError(AccountKitError accountKitError) {
}
});
}
} else {
Log.d("ERROR", "Cannot get your location");
}
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
if (ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(DriverHome.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient.requestLocationUpdates(mLocationRequest, locationCallback, Looper.myLooper());
}
}
excuse me for the nasty code tho :D
and sorry if its a dumb question but idk what im missing here ...
You need to call your displayLocation and getDirection methods only after the map has been initialized (i.e. mMap = googleMap). Check out related Null Pointer Exception and getMapAsync Error
E.g.:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setTrafficEnabled(false);
mMap.setIndoorEnabled(false);
mMap.setBuildingsEnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
try {
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e("Mitkasin", "Style parsing failed.");
}
} catch (Resources.NotFoundException e) {
Log.e("Mitkasin", "Can't find style. Error: ", e);
}
displayLocation();
getDirection();
}
Hope this helps!

Android: Unable to make a location request dialog and get the location on callback

I have followed the official documentation from here to display the location dialog to the user as our app doesn't work without location. The problem is that even when I press the OK button on the dialog, sometimes the onFailure of the task listener gets called, more importantly, even when onSuccess(LocationSettingsResponse locationSettingsResponse) does get called, I'm unable to immediately get the location details, the workaround I made is to create a separate thread to get the details in a loop. I need to know a simpler method to do this.
This took me over 2 days time and I still can't figure what's wrong in my code.
FusedLocationProviderClient client;
TextView textView;
boolean started = false;
double lat = 0;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
client = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(tag, "no perm");
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
} else
work();
}
void work() {
if (!isLocationEnabled()) createLocationRequest();
else locationDetails();
}
int t = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e(tag, "activity result");
work();
}
void locationDetails() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
client.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
if(lat!=0)return;
lat = location.getLatitude();
textView.setText("location: lat" + lat + " lng" + location.getLongitude());
Log.e(tag, "happy");
} else {
repeatedRequests();
Log.e(tag, "null location");
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
} else work();
}
void createLocationRequest() {
final LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
final SettingsClient settingsclient = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = settingsclient.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
repeatedRequests();
Log.e(tag, "success");
}
});
task.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException) {
Log.e(tag, "failure" + e.getLocalizedMessage());
// repeatedRequests();
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
Log.e(tag, "erorr " + sendEx.getLocalizedMessage());
// Ignore the error.
}
}
}
});
}
void repeatedRequests() {
if (!started) {
started = true;
Log.e(tag, "Thread started");
new Thread(new Runnable() {
#Override
public void run() {
while (lat == 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
t++;
if (t > 50) break;
Log.e(tag, "repeat");
runOnUiThread(new Runnable() {
#Override
public void run() {
locationDetails();
}
});
}
}
}).start();
}
}
boolean isLocationEnabled() {
int locationMode = 0;
try {
locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}
Try to set mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
just for yours samsung, in my case it works but keep in the mind that locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) will return false in this case.
getLastLocation()
it works when there is at least one subscriber to the google service..
You need to subscribe, and if you do not need to constantly update the coordinates, you can immediately unsubscribe...
val client = LocationServices.getFusedLocationProviderClient(this)
client.requestLocationUpdates(locationRequest, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
//job.invoke()
client.removeLocationUpdates(this)
}
}, Looper.myLooper())

Can't get latitude and longitude in AsyncTask

I'm working with Weather Underground API where I can get weather of a place in 2 ways:
Writing directly the name of the city and nation (example:http://api.wunderground.com/api/*MyKey*/conditions/q/It/Venice.json)
Get the weather of every place have latitude/longitude (example:http://api.wunderground.com/api/*MyKey*/conditions/q/45.43972222,12.33194444.json)
I'm interested in the second way so I'm trying to get my position (that works in an Activity).
FirstActivity.java: (the position is displayed with no problem)
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation())
{
String stringLatitude = String.valueOf(gpsTracker.latitude);
TextView textview1 = (TextView)findViewById(R.id.fieldLatitude);
textview1.setText(stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
TextView textview2 = (TextView)findViewById(R.id.fieldLongitude);
textview2.setText(stringLongitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
}
AsyncTask:
public class Conditions extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_conditions);
new WeatherConditions(this).execute();
}
private class WeatherConditions extends AsyncTask<String, String, String> {
private Context mContext;
public WeatherConditions (Context context){
mContext = context;
}
#Override
protected String doInBackground(String... uri) {
GPSTracker gpsTracker = new GPSTracker(mContext);
String latitudine = null;
String longitudine = null;
if (gpsTracker.canGetLocation())
{
latitudine = String.valueOf(gpsTracker.latitude);
longitudine = String.valueOf(gpsTracker.longitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gpsTracker.showSettingsAlert();
}
String responseString = null;
try {
HttpClient client = new DefaultHttpClient();
URI apiCall = new URI("api.wunderground.com/api/51cda8abeca78e10/conditions/q/"
+ latitudine
+","
+ longitudine
+".json");
HttpGet request = new HttpGet();
request.setURI(apiCall);
HttpResponse response = client.execute(request);
responseString = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
Log.e("TAG", "some sort of problem encountered", e);
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
...
}
}
}
Where I get this message in the LogCat: Can't create handler inside thread that has not called Looper.prepare()
Here's GPSTracker.java:
public class GPSTracker extends Service implements LocationListener{
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
}
else
{
this.canGetLocation = true;
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation()
{
return this.canGetLocation;
}
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("Attenzione!");
alertDialog.setMessage("Abilita il GPS");
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("CLOSE", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
return geocoder.getFromLocation(latitude, longitude, 1);
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getAddressLine(0);
}
else
{
return null;
}
}
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getLocality();
}
else
{
return null;
}
}
public String getSubLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getSubLocality();
}
else
{
return null;
}
}
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getPostalCode();
}
else
{
return null;
}
}
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
return address.getCountryName();
}
else
{
return null;
}
}
#Override
public void onLocationChanged(Location location)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
In GPSTracker.java, since getLocation() has context of async task attached to it and looper is not attached to it.
A quick workaround to solve this problem is add Looper.getMainLooper() with requestLocationUpdates, this will attach main looper thread callback with request.
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this, Looper.getMainLooper()
);

Categories