Having problems with google maps on Fragments layout - java

I made an activity with google maps displayed, but I'd like to change it to Fragments, When I do that i get lots of errors.
I have problems with getMapAsync on the initmap method.
public class TAXIActivity extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private MapView mapView;
ArrayList LatitudeList = new ArrayList();
ArrayList LongitudeList = new ArrayList();
private FusedLocationProviderClient mFusedLocationProviderClient;
private Boolean mLocationPermissionsGranted = false;
private static final float DEFAULT_ZOOM = 15f;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_taxi, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_taxi);
/*
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
*/
getLocationPermission();
//someMethod();
}
public void onViewCreated (View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initMap();
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(getContext(), "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d("TAXIActivity", "onMapReady: map is ready");
mMap = googleMap;
someMethod();
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
//mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
//Log.d("TEST", "BBB");
//String LatMarkers = LatitudeList.toString();
//String LongMarkers = LongitudeList.toString();
//Log.d("TEST", "AAA");
/*
double latitude = Double.parseDouble(LatMarkers);
double longitude = Double.parseDouble(LongMarkers);
LatLng location = new LatLng(latitude, longitude);
//Log.d("TEST", "CCC");
mMap.addMarker(new MarkerOptions().position(location).title("Camera Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
*/
//Log.d("TEST", "DDD");
}
OkHttpClient client = new OkHttpClient();
void someMethod() {
try {
String jsonData = new TAXIAPI(client).execute().get();
JSONObject object = new JSONObject(jsonData);
JSONArray RunningArray = object.getJSONArray("value");
for (int i = 0; i < RunningArray.length(); ++i) {
JSONObject objectInner = new JSONObject(RunningArray.getString(i));
String Latitude = objectInner.getString("Latitude");
String Longitude = objectInner.getString("Longitude");
double lat = Double.parseDouble(Latitude);
double lng = Double.parseDouble(Longitude);
LatLng location = new LatLng(lat, lng);
mMap.addMarker(new MarkerOptions().position(location).title("Taxi Location"));
//mMap.moveCamera(CameraUpdateFactory.newLatLng(location));//this will make camera focus on the last marker location
//LatitudeList.add(Latitude);
//LongitudeList.add(Longitude);
Log.d("APIActivity", " " + Latitude + " " + Longitude);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDeviceLocation() {
Log.d("TAXIActivity", "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
try {
if (mLocationPermissionsGranted) {
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d("TAXIActivity", "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
} else {
Log.d("TAXIActivity", "onComplete: current location is null");
Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (SecurityException e) {
Log.e("TAXIActivity", "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d("TAXIActivity", "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap() {
Log.d("TAXIActivity", "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(TAXIActivity.this);
}
private void getLocationPermission() {
Log.d("TAXIActivity", "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(getActivity(),
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d("TAXIActivity", "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
Log.d("TAXIActivity", "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d("TAXIActivity", "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
}
Error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
at com.example.assignment1.TAXIActivity.initMap(TAXIActivity.java:199)
at com.example.assignment1.TAXIActivity.getLocationPermission(TAXIActivity.java:213)
at com.example.assignment1.TAXIActivity.onCreate(TAXIActivity.java:72)

You're getting google map fragment before your fragment view is created.
Right now you're doing, onCreate then getLocationPermission then initMap then .findFragmentById. Your google map fragment is not initialized at this point, that's why you're getting a null pointer exception when calling .getMapAsync.
Two solutions. Move you getLocationPermission to onViewCreated or remove initMap from getLocationPermission.
I'd do the second one, because Google Map doesn't need location permission.

Related

My lastLocation shows null on a few devices and crashes my app

My lastLocation show in few devices and cruch my app
Here is my code:
...............................................................................................................................................................................................................................................................
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
private MarkerOptions marker;
private Location location;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.activity_maps, container, false);
return mView;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = view.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
addMarker();
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
double lat = location.getLatitude();
double lng = location.getLongitude();
String lat1 = String.valueOf(lat);
String lng1 = String.valueOf(lng);
//Define list to get all latLng for the route
ArrayList<LatLng> path = new ArrayList<LatLng>();
//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(API_KEY)
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, lat1 + ", " + lng1, "31.742462, 34.985447");
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polyLines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs != null) {
for (int i = 0; i < route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j = 0; j < leg.steps.length; j++) {
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length > 0) {
for (int k = 0; k < step.steps.length; k++) {
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch (Exception ignored) {
}
//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
googleMap.addPolyline(opts);
}
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(31.742462, 34.985447), 10));
}
public void addMarker() {
marker = new MarkerOptions().position(new LatLng(31.742462, 34.985447)).title("בית הכנסת - נווה צדק").icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mGoogleMap.addMarker(marker);
mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
Toast.makeText(getContext(), "בית הכנסת - נווה צדק", Toast.LENGTH_SHORT).show();
return true;
}
});
}

How to draw a route from current location to a markerpoint on Android Google Maps?

I'm new creating apps and I want to show a drawn route in a Google Map starting from the current location. I've just found how to get the current location, but now I'm stuck in the second part, which is drawing the route from the current location to another marker point.
Here is my code:
`public class Trazo_Rutas extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient googleApiClient;
LocationRequest locationRequest;
Location lastLocation;
Marker userLocation;
private static final int Request_User_Location_Code = 99;
PlaceAutocompleteFragment placeAutoComplete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trazo__rutas);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkUserLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
//AutoComplete search bar
placeAutoComplete = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
//get latlong for corners for specified place
LatLng corner1 = new LatLng(25.64379, -103.60966);
LatLng corner2 = new LatLng(25.64317, -103.20935);
LatLng corner3 = new LatLng(25.43872, -103.61104);
LatLng corner4 = new LatLng(25.43748, -103.20866);
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(corner1);
builder.include(corner2);
builder.include(corner3);
builder.include(corner4);
LatLngBounds bounds = builder.build();
//add them to builder
int width = getResources().getDisplayMetrics().widthPixels;
int height = getResources().getDisplayMetrics().heightPixels;
// 20% padding
int padding = (int) (width * 0.20);
//set latlng bounds
mMap.setLatLngBoundsForCameraTarget(bounds);
//move camera to fill the bound to screen
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding));
//set zoom to level to current so that you won't be able to zoom out viz. move outside bounds
mMap.setMinZoomPreference(mMap.getCameraPosition().zoom);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
public boolean checkUserLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
} else {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, Request_User_Location_Code);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case Request_User_Location_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (googleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "Se requieren Permisos de Google", Toast.LENGTH_SHORT).show();
finish();
}
return;
}
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
if (userLocation != null) {
userLocation.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.draggable(true);
markerOptions.title("Tu ubicación");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
userLocation = mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1100);
locationRequest.setFastestInterval(1100);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}`
My concern is that I don't know how to implement the other marker and draw the route.
Thank you.

Broadcasting data not passed

I'm trying to make an app that tracks device's location using a service and display that location on Google Map. But I feel like the code in service is not executed at all. When I try to retrieve and assign latitude and longitude to a LatLng object I cannot because they are null.
Here is the main activity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1000;
private static final int ERROR_DIALOG_REQUEST = 1001;
private static final float DEFAULT_ZOOM = 15f;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private BroadcastReceiver mBroadcastReceiver;
private LatLng currentLocation;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
if (isServicesOK()) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
}
getLocationPermission();
startMyService();
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume: resumed from service");
if (mBroadcastReceiver == null) {
Log.d(TAG, "onResume: broadcastReceiver == null");
mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: receiving current location");
currentLocation = new LatLng((double) intent.getExtras().get("latitude"),
(double) intent.getExtras().get("longitude"));
}
};
}
Log.d(TAG, "onResume:"+ currentLocation.toString());
registerReceiver(mBroadcastReceiver, new IntentFilter("location"));
}
#Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this.getApplicationContext(), MyService.class);
stopService(intent);
if(mBroadcastReceiver != null){
unregisterReceiver(mBroadcastReceiver);
}
}
private void startMyService() {
Log.d(TAG, "startMyService: starting to track devices location");
Intent intent = new Intent(this.getApplicationContext(), MyService.class);
startService(intent);
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (currentLocation != null) {
moveCamera(currentLocation, 15f);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// auto-generated permission check
return;
}
mMap.setMyLocationEnabled(true);
}
}
private void moveCamera(LatLng latLng, float zoom){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapsActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
public boolean isServicesOK(){
Log.d(TAG, "isServicesOK: checking google services version");
int availvable = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(MapsActivity.this);
if(availvable == ConnectionResult.SUCCESS){
//everything is fine
Log.d(TAG, "isServicesOK: google play services is working");
return true;
}
else if(GoogleApiAvailability.getInstance().isUserResolvableError(availvable)) {
//an error occured but we can resolve it
Log.d(TAG, "isServicesOK: an error occured but we can fix it");
Dialog dialog = GoogleApiAvailability.getInstance().getErrorDialog(MapsActivity.this,availvable, ERROR_DIALOG_REQUEST); dialog.show();
}else{
Toast.makeText(this,"You can't make map request", Toast.LENGTH_SHORT).show();
}
return false;
}
}
The service class:
public class MyService extends Service {
private LocationListener listener;
private LocationManager locationManager;
private static final String TAG = "MyService";
private FusedLocationProviderClient mFusedLocationProviderClient;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("MissingPermission")
#Override
public void onCreate() {
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
Intent intent = new Intent("location");
intent.putExtra("latitude", currentLocation.getLatitude());
intent.putExtra("longitude", currentLocation.getLongitude());
sendBroadcast(intent);
}else{
Log.d(TAG, "onComplete: current location is null");
}
}
});
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
}
I know how to get the current location and update the map but without using a service. But I need to make it this way - with a service. And I can't figure out where my mistake is.

How can I get data from Nearby Places into Listview?

Which methods do I have to include to my code to pass the data to list view?
I want to show the nearby places using ListView. It only show the nearby places on the map by clicking the buttons as shown below. When I click the "Nearby School" button it displays the nearby school on the map, now I want it to display the nearby schools using listview. How can I do that?
public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
double latitude;
double longitude;
private int PROXIMITY_RADIUS = 10000;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
ListView lvMap;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
//Check if Google Play Services Available or not
if (!CheckGooglePlayServices()) {
Log.d("onCreate", "Finishing test case since Google Play Services are not available");
finish();
}
else {
Log.d("onCreate","Google Play Services available.");
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.maps);
mapFragment.getMapAsync(this);
}
private boolean CheckGooglePlayServices() {
GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
int result = googleAPI.isGooglePlayServicesAvailable(this);
if(result != ConnectionResult.SUCCESS) {
if(googleAPI.isUserResolvableError(result)) {
googleAPI.getErrorDialog(this, result,
0).show();
}
return false;
}
return true;
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize 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) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
Button btnRestaurant = (Button) findViewById(R.id.btnRestaurant);
btnRestaurant.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Restaurant);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});
Button btnHospital = (Button) findViewById(R.id.btnHospital);
btnHospital.setOnClickListener(new View.OnClickListener() {
String Hospital = "hospital";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
String url = getUrl(latitude, longitude, Hospital);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Hospitals", Toast.LENGTH_LONG).show();
}
});
Button btnSchool = (Button) findViewById(R.id.btnSchool);
btnSchool.setOnClickListener(new View.OnClickListener() {
String School = "school";
#Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
mMap.clear();
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
String url = getUrl(latitude, longitude, School);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
getNearbyPlacesData.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Schools", Toast.LENGTH_LONG).show();
}
});
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.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(mGoogleApiClient, mLocationRequest, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlacesUrl.append("&type=" + nearbyPlace);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + "AIzaSyATuUiZUkEc_UgHuqsBJa1oqaODI-3mLs0");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
Log.d("onLocationChanged", "entered");
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
latitude = location.getLatitude();
longitude = location.getLongitude();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
Toast.makeText(MapsActivity.this,"Your Current Location", Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d("onLocationChanged", "Removing Location Updates");
}
Log.d("onLocationChanged", "Exit");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] 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) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}

Getting My Location Null pointer in Fragment in GoogleMap API v2

I'm trying to get my location on click of save button & store that in
database.
Problem:
When I'm trying to get my location it shows me null pointer exception.
Can anyone tell me whats wrong in my code?
My code:
public class OthersFragment extends Fragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
View view;
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Double latitude;
Double longitude;
String strplace;
public static OthersFragment newInstance() {
OthersFragment fragment = new OthersFragment();
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// mGoogleApiClient = new GoogleApiClient.Builder(getContext())
// .addApi(LocationServices.API)
// .addConnectionCallbacks(this)
// .addOnConnectionFailedListener(this)
// .build();
view = inflater.inflate(R.layout.fragment_other, null, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
Location mylocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
ShowPopUp(mylocation);
return true;
}
});
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
private void ShowPopUp(final Location mylocation) {
int popupWidth = 300;
int popupHeight = 150;
// Inflate the popup_layout.xml
LinearLayout viewGroup = (LinearLayout)view.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.popup, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow();
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 30;
int OFFSET_Y = 30;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY, + OFFSET_X, OFFSET_Y);
// Getting a reference to Close button, and close the popup when clicked.
Button save = (Button) layout.findViewById(R.id.save);
Button retrieve = (Button) layout.findViewById(R.id.retrieve);
final EditText place = (EditText)layout.findViewById(R.id.place);
final EditText phone = (EditText)layout.findViewById(R.id.phone);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "save";
String strplace = place.getText().toString();
String strphone = phone.getText().toString();
new storePoints().execute(strplace,String.valueOf(mylocation.getLatitude()), String.valueOf(mylocation.getLongitude()), action);
popup.dismiss();
}
});
retrieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "retrieve";
strplace = place.getText().toString();
String strphone = phone.getText().toString();
new retrievePoints().execute(strplace, action);
popup.dismiss();
}
});
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
private class storePoints extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
String place = (String) params[0];
// String phone = (String) params[1];
String latitude = (String) params[1];
String longitude = (String) params[2];
String action = (String) params[3];
String link = "http://192.168.0.152/prestige/saveCoord.php";
// String link = "http://10.0.2.2/coordinates/coord.php";
String data = URLEncoder.encode("station_name", "UTF-8") + "=" + URLEncoder.encode(place, "UTF-8");
// data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
data += "&" + URLEncoder.encode("latitude", "UTF-8") + "=" + URLEncoder.encode(latitude, "UTF-8");
data += "&" + URLEncoder.encode("longitude", "UTF-8") + "=" + URLEncoder.encode(longitude, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(OthersFragment.this.getContext(), result, Toast.LENGTH_LONG).show();
}
}
private class retrievePoints extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
try {
String place = (String) params[0];
String phone = (String) params[1];
String link = "http://192.168.0.152/prestige/retCoord.php";
// String link = "http://10.0.2.2/coordinates/retCoord.php";
String data = URLEncoder.encode("station_name", "UTF-8") + "=" + URLEncoder.encode(place, "UTF-8");
data += "&" + URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(phone, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
// Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
try {
mMap.clear(); // clear all the markers on the map.
JSONArray loc_arr = new JSONArray(result);
for (int i = 0; i < loc_arr.length(); i++){
JSONObject loc_obj = loc_arr.getJSONObject(i);
Double latitude = Double.valueOf((loc_obj.getString("latitude")));
Double longitude = Double.valueOf((loc_obj.getString("longitude")));
String place = loc_obj.getString("station_name");
// Toast.makeText(MainActivity.this, "latitude: "+latitude +"\t Longitude: " + longitude+"\t Place: "+place, Toast.LENGTH_SHORT).show();
Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Place: "+place).snippet("Latitude: " +latitude+",Longitude: "+longitude));
marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude),28));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Error Log:
06-20 12:30:42.740 6682-6682/com.example.barbegambino.apslocate E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.barbegambino.apslocate, PID: 6682
java.lang.NullPointerException
at com.example.barbegambino.apslocate.fragments.OthersFragment$2.onClick(OthersFragment.java:166)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18789)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
at dalvik.system.NativeStart.main(Native Method)
For example try to get last-known location like below,
public class MapExample extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize 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) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.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(mGoogleApiClient, mLocationRequest, this);
}
else{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
// work with your last location.
} else {
Toast.makeText(this, R.string.no_location, Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onConnectionSuspended(int i) {
}
#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("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] 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) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}
I added this and it worked for me.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_entry, null, false);
//added
if (!isGooglePlayServicesAvailable()) {
Toast.makeText(getContext(), "Google Play Services is not available", Toast.LENGTH_LONG).show();
getActivity().finish();
}
mGoogleApiClient = new GoogleApiClient.Builder(getContext())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
This also i added
#Override
public void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, getActivity(), 0).show();
Toast.makeText(getContext(), "Google Play Services is not Available", Toast.LENGTH_LONG).show();
return false;
}
}

Categories

Resources