user2581076
user2581076

Reputation:

error in getting latitude and longitude from android device

Here is my code to display Login user on google map and getting user location details(i.e latitude and longitude)

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start);
    googleMap = ((MapFragment) getFragmentManager().findFragmentById(
            R.id.map)).getMap();
    googleMap.setMyLocationEnabled(true);
    // Creating location manager and location classes instances
    locationManager = (LocationManager) this
            .getSystemService(LOCATION_SERVICE);
     location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
     CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(location.getLatitude(), location.getLongitude())).zoom(9).build();

googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

.tried by debugging here able to display user on map done successfully but for getting location details getting null poiner exception,i am working on android mobile ( settings configured ) but i am not getting why null pointer exception.suggest me suitable solution.(here using wifi connection. )

Upvotes: 0

Views: 507

Answers (2)

cYrixmorten
cYrixmorten

Reputation: 7108

A nice gps tracker guide: http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

Just needed to add this.mLocation = location in onLocationChanged


googleMap can be null, of view has not been fully created.

location can be null if GPS is not enabled on phone.

Search for and follow some guides on the subject. 

Upvotes: 1

tyczj
tyczj

Reputation: 73721

you probably do not have a location at the time you call getLastKnownLocation which would be why you are getting null. so before you use the location object you should check to make sure it is not null. for example if(location != null)

you should probably look at using the new Location API or even the built in google map location manager as they get better results

Upvotes: 1

Related Questions