Sudipta Som
Sudipta Som

Reputation: 6567

How to get present location through gps in Android

How to get the present location through GPS in android. I am using the following code..

But when i am using LastKnowKnown location it is throwing null pointer exception.. Code is given below

Please any body help.. How to fix it?

public void getlocation()
    {       

        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
        locationListener = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

    }

class MyLocationListener implements LocationListener 
 {
     String a;
     String b;
     String c;


    public void onLocationChanged(Location loc) 
    {
        if (loc != null) {

            LAT = loc.getLatitude();
            LONG = loc.getLongitude();  
            a=Double.toString(LAT);
            b=Double.toString(LONG);
            c="-----LAT is:"+a+"  "+"LONG is--------:"+b;
            System.out.println(c);



        }
    }

 public void getPresentLocation() {
        String a;
         String b;
         String c;

        lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);  
        LAT = location.getLatitude();
        LONG = location.getLongitude();
        a=Double.toString(LAT);
        b=Double.toString(LONG);
        c="-----LAT is:"+a+"  "+"LONG is--------:"+b;
        System.out.println(c);

Upvotes: 0

Views: 745

Answers (1)

Reno
Reno

Reputation: 33792

From the documentation

If the provider is currently disabled, null is returned.

So if there is a possibility of the api returning null, keep null checks in place so avoid the exception. Just like you did in the first example.

I think that there was no cached fix yet in your case.

Upvotes: 2

Related Questions