0

I am trying to find out current latitude and longitude of android device but I am getting java.lang.nullpointerexception and app is force closing.even though i get refrence from here and used the code from the answer which was accepted as correct: How to get Android GPS location my code is:

try{
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
             Criteria criteria = new Criteria();
             String bestProvider = locationManager.getBestProvider(criteria, false);
             Location location = locationManager.getLastKnownLocation(bestProvider);


        double latit=location.getLatitude();
        double longit=location.getLongitude();
        Toast.makeText(getApplicationContext(),"Your Location is:\nLatitude:\t"+latit+"\nLongitude:\t"+longit,Toast.LENGTH_LONG).show();
            }catch(Exception ex){
                Toast.makeText(getApplicationContext(), "Error:"+ex,Toast.LENGTH_LONG).show();
            }
Community
  • 1
  • 1
Kme
  • 103
  • 1
  • 11

1 Answers1

0

I would bet that your location variable is null and that's why you're getting the NullPointerException. When you call LocationManager.getLastKnownLocation() it can return null if there is no last known location. Your best bet is to request location updates using one of the LocationManager.requestLocationUpdates() methods and passing in a LocationListener.

CaseyB
  • 24,780
  • 14
  • 77
  • 112
  • I have never used this method.please show me how to use this. – Kme May 28 '14 at 18:20
  • The best example that I could recommend come from Reto Meier's blog. http://android-developers.blogspot.de/2011/06/deep-dive-into-location.html – CaseyB May 28 '14 at 18:23