1

I'm trying to use MyLocation class from here. In code below I need to access variable currentLat and currentLon anywhere inside the class instantiating MyLocation. I don't know how to access value of currentLat and currentLon

LocationResult locationResult = new LocationResult(){ @Override public void gotLocation(Location location){ currentLat = location.getLatitude(); currentLon = location.getLongitude(); }; } MyLocation myLocation = new MyLocation(); myLocation.getLocation(this, locationResult);

Suppose I want here

Double x =currentLoc;

how to I get that? Any help would be appreciated

Community
  • 1
  • 1
carefree
  • 95
  • 1
  • 1
  • 4

2 Answers2

0

instead of anonymous class use your own that extends/implments LocationResult class/interface and add getter like this

    class MyLocationResult extends/implments LocationResult{
    double currentLat;
    double currentLon;

    @Override 
    public void gotLocation(Location location){ 
        currentLat = location.getLatitude(); 
        currentLon = location.getLongitude(); 
    };
    public double getCurrentLat(){
       return currentLat;
    }
    public double getCurrentLon (){
       return currentLon ;
    }
}

then you can write

MyLocationResult locationResult = new MyLocationResult();
MyLocation myLocation = new MyLocation(); 
myLocation.getLocation(this, locationResult);

and whenever you need currentLat or currentLon you can write

locationResult.getCurrentLat();
Vilen
  • 5,061
  • 3
  • 28
  • 39
  • It's returning 0.0 I tried setter too but no help. Inside gotLocation method of MYLocationResult value displayed but outside that everywhere it's 0.0 – carefree Jan 14 '15 at 11:11
  • well you can call getCurrentLat only when gotLocation() was called before , so if you require getCurrentLat but it is not set yet you will have 0.0 – Vilen Jan 14 '15 at 11:13
0

You can use static modifiers for your variables and define them globally..

public static double currentLat; // defined globally...
public static double currentLon;

LocationResult locationResult = new LocationResult(){
   @Override
      public void  gotLocation(Location location){
      currentLat =location.getLatitude(); // assuming getLatitude() returns double or int
      currentLon = location.getLongitude();
    };
}
MyLocation myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);

Now you can access them anywhere

double x =currentLon;
double y =currentLat;
Sharp Edge
  • 4,144
  • 2
  • 27
  • 41
  • I'm getting 0.0 but inside LocationResult value is not 0 – carefree Jan 14 '15 at 11:13
  • Are you sure the value is not `0.0` ? Trying Logging the values right after this line `currentLat =location.getLatitude();` put this line and then try ! `Log.e("method1 returns",""+location.getLatitude());` – Sharp Edge Jan 14 '15 at 11:17