简体   繁体   中英

Android location always null

I had my application to find location working, but I changed some code and now the location always returns null. Ashamedly I am not sure what code I had changed, but I just cant seem to get it working.

Can anyone see why this returns null? I have been working on this all day with no joy. code below:

....imports....

public class Clue extends Activity {

public static double latitude;
public static double longitude;
Criteria criteria;
LocationManager lm;
LocationListener ll;
Location location;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  setContentView(R.layout.questions);

  criteria = new Criteria();
  criteria.setAccuracy(Criteria.ACCURACY_FINE);
  lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  ll = new MyLocationListener();
  lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);

areWeThereYet();
}

   private void areWeThereYet()
  {
      if(weAreThere())
      {
      showMsgBox("There");  
    }
  else if(location!=null)
      toastMsg("not there");
       }

    private boolean weAreThere() {

location = getLocation(); 
if (location!=null)
{
longitude = location.getLongitude();
latitude = location.getLatitude();
return inCorrectPlace(question);
}
else
{
    toastMsg("Location not ready yet");
    return false;
}
}

private Location getLocation() {
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
      return lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

}

public class MyLocationListener implements LocationListener
{
    public void onLocationChanged(Location loc)
    {        
         Clue.longitude = loc.getLongitude();
         Clue.latitude = loc.getLatitude();
    }
}

I have added all permissions and simplified my code so you can all see what's going on.

Thanks,

Ben

It's null because when you first start your activity in onCreate it isn't ready yet. When you eventually get the location update via onLocationChanged, you set the lat/lon on your Clue class but that's it... nothing re-calls your areWeThereYet method. You'd need to call that method after updating your location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM