I'm having a problem with my android app where I cannot retrieve the devices current location. From debugging the app it appears that onLocationChange within my LocationListener is not firing.
I have set up requestLocationUpdates to work with my LocationListener, along with an output to the Log within onLocationChange but I am receiving nothing.
I've also noticed that there's no GPS icon appearing in the top bar of the phone when I'm using the app but if I switch over to the Google Maps app, the icon appears instantly...I'm struggling with this at this point so any help would really be appreciated. Thanks.
MapFragment.java:
public class MapFragment extends Fragment implements OnMapReadyCallback {
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private OnFragmentInteractionListener mListener;
private SupportMapFragment mapFragment;
private GoogleMap googleMap;
LocationManager locationManager;
public MapFragment() {
// Required empty public constructor
}
public static MapFragment newInstance() {
MapFragment fragment = new MapFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.onCreate(savedInstanceState);
mapFragment.onResume();
mapFragment.getMapAsync(this);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
checkLocationPermission();
}
#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) {
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
}
} else {
// functionality that depends on this permission.
}
return;
}
}
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
//your code here
Log.v("LOCATION UPDATE", "IN ON LOCATION CHANGE, lat=" + location.getLatitude() + ", lon=" + location.getLongitude());
/*
LatLng userPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(userPosition)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin_fill))
.title("Test Pin"));*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
//dialog to ask for permission
new AlertDialog.Builder(getActivity())
.setTitle("Permission")
.setMessage("Need permission")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
}
else {
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
}
return false;
} else {
return true;
}
}
}
Not sure if relevant but
fragment_map.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapFragment" />
Are you sure locationManager.requestLocationUpdates() is executing? Based on this code, if ACCESS_FINE_LOCATION is already granted upon startup, checkLocationPermission() will return true, and nothing ever calls requestLocationUpdates().
Related
I'm working with the map to my app and so I have here a weird error message that it says java.lang.SecurityException: "GPS" location provider requires ACCESS_FINE_LOCATION permission. every time I launch the app and crashes due to this error, though I already have a permission checker.
Here is my code:
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "SOME_KEY";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
#Override
public void onMapReady(GoogleMap googleMap) {
getUserLocation();
}
private void getUserLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
I really do not know where I went wrong from this line of code, to keep my app crashing and give me that error.
Update your code with bellow code may solve your problem
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
boolean isMapReady;
#Override
public void onMapReady(GoogleMap googleMap) {
isMapReady=true;
getUserLocation();
}
private void getUserLocation() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
return;
}
}
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
Now override onRequestPermissionsResult() and check if result is granted and isMapReady flag true then call getUserLocation().
So the solution for this and base on the comments i forgot to put the else statement that if the permission is granted then execute the listener else request a permission.
Updated:
public class FragmentHome extends Fragment implements OnMapReadyCallback {
/*
Set up's
*/
private static final String TAG = "FragmentHome";
/*
Pallete
*/
private MapView mapView;
private GoogleMap gMap;
private static final String MAP_VIEW_BUNDLE_KEY = "AIzaSyDWL-JNHiCXvQefgFh1BdaAflJTveSrHJo";
#SuppressLint("SetJavaScriptEnabled")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view_fragmentInflate = inflater.inflate(R.layout.fragment_fragment_home, container, false);
mapView = (MapView) view_fragmentInflate.findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
return view_fragmentInflate;
}
#Override
public void onMapReady(GoogleMap googleMap) {
checkGPSPermission();
getUserLocation();
}
private void checkGPSPermission() {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) {
// show why is important
}
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
} else {
// granted
}
} else {
// granted
}
}
private void getUserLocation() {
LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
getContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
requestPermissions(new String[] {
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
3000, 0, locationListener);
}
}
}
i want to access current location in fragments , but i am using API 28 and android version 3.2.1. i try everything from internet follow tutorials but i cant access my current location , there is no error in my code but i don't know why i cant access it. when i run my program i just see google default map, no marker etc.
i want to access my location through network provider as well as gps provider if network provider is not available.
i also add permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
for a permission access i am using library from github and for lacation and map
implementation 'pub.devrel:easypermissions:2.0.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
please check my code and guide me how i can access current location my code is in below in my code there is also step counter code but ignore that one.
here is my code
public class HomeActivity extends Fragment implements SensorEventListener, OnMapReadyCallback {
SensorManager sensorManager;
TextView set_steps;
TextView set_calories;
TextView set_distance;
boolean running = false;
private static int steps;
private static int calories;
private static double distance;
private GoogleMap mMap;
LocationManager locationManager;
public static final int Request_User_Location_Code = 99;
GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private final int REQUEST_LOCATION_PERMISSION = 1;
Provider provider;
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_home, container, false);
requestLocationPermission();
stepsCounter();
locationTracker();
return view;
}
void stepsCounter() {
set_steps = (TextView) view.findViewById(R.id.set_steps);
set_calories = (TextView) view.findViewById(R.id.set_calories);
set_distance = (TextView) view.findViewById(R.id.set_distance);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener((SensorEventListener) getActivity(), countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(getActivity(), "Sensor not Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause() {
super.onPause();
running = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (running) {
steps = (int) event.values[0];
set_steps.setText(steps + "");
caloriesCounter();
distanceCover();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
void caloriesCounter() {
calories = steps / 20;
set_calories.setText(calories + "");
}
void distanceCover() {
distance = (double) steps * 0.76;
String distanceText = Double.toString(distance);
set_distance.setText(distanceText);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
void locationTracker() {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ((ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(getActivity(), perms)) {
// Toast.makeText(getActivity(), "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
but remember i am using ApI 28
I'm making an app and I'm using Googlemaps.
Below is my code
I have tried so many different codes but nothing works
My app doesn't work and keeps getting this 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.yoons.honey.Map.onCreate(Map.java:59)
xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Map"
tools:layout_editor_absoluteY="81dp">
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:id="#+id/button"
android:text="my location"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.imaadv.leaynik.ClinicFragment"
android:layout_below="#+id/button"/>
/>
activity code :
public class Map extends AppCompatActivity {
private static final String TAG = "MainActivity";
SupportMapFragment mapFragment;
GoogleMap map;
MarkerOptions myLocationMarker;
private CompassView mCompassView;
private SensorManager mSensorManager;
private boolean mCompassEnabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() { //This is the error I think
#Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "GoogleMap is ready.");
map = googleMap;
onResume();
map.setMyLocationEnabled(true);
}
});
try {
MapsInitializer.initialize(this);
} catch (Exception e) {
e.printStackTrace();
}
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
requestMyLocation();
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
boolean sideBottom = true;
mCompassView = new CompassView(this);
mCompassView.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(sideBottom ? RelativeLayout.ALIGN_PARENT_BOTTOM : RelativeLayout.ALIGN_PARENT_TOP);
((ViewGroup) mapFragment.getView()).addView(mCompassView, params);
mCompassEnabled = true;
}
private void requestMyLocation() {
LocationManager manager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
long minTime = 10000;
float minDistance = 0;
manager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
minTime,
minDistance,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
showCurrentLocation(lastLocation);
}
manager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
minTime,
minDistance,
new LocationListener() {
#Override
public void onLocationChanged(Location location) {
showCurrentLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void showCurrentLocation(Location location) {
LatLng curPoint = new LatLng(location.getLatitude(), location.getLongitude());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(curPoint, 15));
showMyLocationMarker(location);
}
private void showMyLocationMarker(Location location) {
if (myLocationMarker == null) {
myLocationMarker = new MarkerOptions();
myLocationMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
myLocationMarker.title("�뿈 �궡 �쐞移?n");
myLocationMarker.snippet("�뿈 GPS濡� �솗�씤�븳 �쐞移�");
myLocationMarker.icon(BitmapDescriptorFactory.fromResource(R.mipmap.mylocation));
map.addMarker(myLocationMarker);
} else {
myLocationMarker.position(new LatLng(location.getLatitude(), location.getLongitude()));
}
}
#Override
protected void onPause() {
super.onPause();
if (map != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
map.setMyLocationEnabled(false);
}
if (mCompassEnabled) {
mSensorManager.unregisterListener(mListener);
}
}
#Override
protected void onResume() {
super.onResume();
if (map != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}
map.setMyLocationEnabled(true);
}
if(mCompassEnabled) {
mSensorManager.registerListener(mListener, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_UI);
}
}
private final SensorEventListener mListener = new SensorEventListener() {
private int iOrientation = Surface.ROTATION_0;
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
if (iOrientation < 0) {
iOrientation = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
}
mCompassView.setAzimuth(event.values[0] + 90 * iOrientation);
mCompassView.invalidate();
}
};
}
I looked through a lot of questions like this.
I tried inflating my view but when I tried
View view = inflater.inflate(R.layout.map, null, false);
the inflater had a red line to it. It said it couldn't resolve symbol 'inflater'
and also when I tried getChildFragmentManager instead of getSupportFragmentManager I also had a red line
And I think I have got all the users-permissions
I want a marker to show my current location. All permissions needed are added. When I comment out mMap.addMarker and mMap.moveCamera the app is working and Googlemaps is shown. If I let one of those two in my code the app crashes before the map even opens.
I've tried with removing the marker if it isn't null but this doesn't solve the problem.
Do you guys have any idea how I can get the app working?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private List<LatLng> fountain = null;
private LocationManager locationManager;
private double posLat;
private double posLng;
private LatLng position;
private Marker mPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
startGPS();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(48.16786112327462, 16.383984438313828);
mPosition = mMap.addMarker(new MarkerOptions().position(sydney).title("Your Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
//--------------------------------------------GPS Listener---------------------------------------
public void startGPS() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 5);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
onLocationChanged(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 5: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
getDialog2("Keine Erlaubnis für GPS").show();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//----------------------------Helper Methods-----------------------------------------------
public Dialog getDialog2(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder.create();
}
public Dialog getDialog(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Okay, I already solved the problem. So I post the solution here.
I have implemented on the MapsActivity the LocationListener interface and for some reason it doesn't work this way. I can retrieve the geocoordinates but as soon as I want to move the camera or add a marker it the app crashes as it gets opened.
I don't know why, but instead of:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this)
I undo the implementation of the LocationListener and just create a new one at the position of ,,this":
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
and this way it works without problem.
I'm trying to implement location permissions in Android Marshmallow. I created a small test application, and everything is working perfectly. But when I copy that same code into my real application, the dialog "Allow [app name] to access this device's location?" never appears.
I can step through the debugger and see that ActivityCompat.requestPermissions() is called when it should be.
The only difference I can think of is that the real app has a lot more going on. The map activity is created from within a ScrollableTabActivity, like this:
this.addTab(getString(R.string.map), R.drawable.iconmap,
RadioStateDrawable.SHADE_GRAY,
RadioStateDrawable.SHADE_BLUE, new Intent(this, MapsActivity.class));
Do I need to think about threads, or anything like that? Or creating the activity in a different way?
Here's the full source code to the sample activity (where everything works):
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Button gpsButton;
private static String[] LOCATION_PERMISSIONS = {Manifest.permission.ACCESS_FINE_LOCATION};
private static int ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE = 1;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
gpsButton = (Button) findViewById(R.id.GPS);
gpsButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
requestLocationPermissions();
}
});
}
private void requestLocationPermissions()
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
new AlertDialog.Builder(MapsActivity.this)
.setMessage("Without access to your location, the app's location function cannot be used. Will you allow this access?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
ActivityCompat.requestPermissions(MapsActivity.this,
LOCATION_PERMISSIONS, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}).setNegativeButton(R.string.no, null).show();
}
else
{
ActivityCompat.requestPermissions(this, LOCATION_PERMISSIONS, ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE);
}
}
else
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults)
{
if (requestCode == ACCESS_FINE_LOCATION_PERMISSION_REQUEST_CODE)
{
if (verifyPermissions(grantResults))
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else
{
new AlertDialog.Builder(MapsActivity.this)
.setMessage("Without access to your location, the app's location function cannot be used.")
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
}
}).show();
}
}
}
private void updateUserLocation(Location location)
{
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
locationManager.removeUpdates(this);
}
public static boolean verifyPermissions(int[] grantResults)
{
boolean verified = false;
for (int result : grantResults)
{
if (result == PackageManager.PERMISSION_GRANTED)
{
verified = true;
}
}
return verified;
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public void onLocationChanged(Location location)
{
updateUserLocation(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onProviderDisabled(String provider)
{
}
}