2011-12-15 212 views
1

我讓我的應用程序找到位置工作,但我更改了一些代碼,現在位置總是返回null。慚愧的是,我不確定我改變了哪些代碼,但我似乎無法讓它工作。Android位置始終爲空

任何人都可以看到爲什麼這返回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(); 
    } 
} 

我添加了所有的權限和簡化我的代碼,所以你都可以看到發生了什麼事情。

感謝,

+0

只是對未來的建議:把你的代碼放在版本控制中! – 2011-12-15 18:37:22

+0

我通常這樣做,這是一個小項目,所以我沒有打擾:希望我現在做了! – 2011-12-15 18:39:35

回答

1

這是null,因爲當你第一次啓動的onCreate您的活動是還沒有準備好。當你最終通過onLocationChanged獲得位置更新時,你可以在你的Clue類上設置緯度/經度,但就是這樣......沒有什麼可以重新調用你的areWeThereYet方法。更新您的位置後,您需要調用該方法。