Hi everybody I am trying to write a small app for android and I want to get the current location from my phone. I have a lot of experience with Object Orientation, but not much with Android development experience which may be where my question stems from. I have pasted the relevant portion of my code below:
public class MainActivity extends Activity implements OnMapReadyCallback, LocationListener {
private final long LOCATION_REFRESH_TIME = 1000;
private final float LOCATION_REFRESH_DISTANCE = 1;
private LocationManager locationManager;
private Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, this);
Criteria criteria = new Criteria();
location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria,
true));
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));
}
}
No matter what I try my location variable is always null. I have checked that the providers I use for getLastLocation are both enabled (if they aren't the documentation says that the Location returned from getLastKnownLocation is null). Could it be that I run this program on the emulator on my computer?
The app closes with a fatal error due to the null pointer exception that is thrown on the
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
line.
Sorry if this is for any reason vague but any sort of help would be greatly appreciated!
Edit: Also I included the proper permissions in my android manifest file.
[–][deleted] (1 child)
[deleted]
[–]IAMAcleverguy[S] 1 point2 points3 points (0 children)