Android位置始终为null

时间:2011-12-15 18:34:53

标签: java android location locationmanager

我的应用程序找到了位置工作,但我更改了一些代码,现在位置始终返回null。惭愧的是我不确定我改变了什么代码,但我似乎无法让它发挥作用。

有谁能看到为什么这会返回null?我整天都在努力工作,没有任何快乐。  代码如下:

....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();
    }
}

我已添加了所有权限并简化了我的代码,因此您可以看到正在发生的事情。

谢谢,

1 个答案:

答案 0 :(得分:1)

它是null,因为当您第一次在onCreate中开始活动时,它还没有准备好。当您最终通过onLocationChanged获取位置更新时,您在Clue类上设置了lat / lon,但就是这样......没有任何重新调用您的areWeThereYet方法。更新位置后,您需要调用该方法。

相关问题