2011-04-24 101 views
0

嗨,我一直在嘗試從書中的示例運行此代碼,但我得到的是空值傳遞給變量,所以我只收到消息作爲「您當前的位置是:沒有位置找到GPS座標不被檢索

清單文件是如下

<application android:icon="@drawable/icon" android:label="@string/app_name"> 
    <activity android:name=".MainActivity" 
       android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

</application> 

main.xml中的文件是

<?xml version="1.0" encoding="utf-8"?> 
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:orientation="vertical" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
    > 
    <TextView 
     android:id="@+id/myLocationText" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="@string/hello" 
     /> 
    </LinearLayout> 

最後是MainActivity.java

package com.snooze.android.geopositioning; 
    import android.app.Activity; 
    import android.content.Context; 
    import android.location.Location; 
    import android.location.LocationManager; 
    import android.os.Bundle; 
    import android.widget.TextView; 
    public class MainActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    LocationManager locationManager; 
    String context = Context.LOCATION_SERVICE; 
    locationManager = (LocationManager)getSystemService(context); 
    String provider = LocationManager.GPS_PROVIDER; 
    Location location = locationManager.getLastKnownLocation(provider); 
    updateWithNewLocation(location); 
    } 
    public void updateWithNewLocation(Location location) 
    { 
String latLongString; 
TextView myLocationText; 
    myLocationText = (TextView)findViewById(R.id.myLocationText); 
    if (location != null) 
    { 
    double lat = location.getLatitude(); 
    double lng = location.getLongitude(); 
    latLongString = "Lat:" + String.valueOf(lat) + "\nLong:" + String.valueOf(lng); 
    } 
    else 
    { 
    latLongString = "No location found"; 
    } 
    myLocationText.setText("Your Current Position is:\n" + latLongString); 
    } 
    } 

這是我的第一個項目,所以我不熟悉的幾個運作的,但我複製一切正如書中所說,但它不起作用。在許多網站上嘗試過各種各樣的東西,以及來自這個論壇的答案....但是無濟於事。 我認爲,座標不會傳遞給變量。 請幫忙

回答

0

你應該在代碼中使用縮進和段落,使其更具可讀性。

此外,爲了顯示地圖,還有一個'MapActivity',它已經爲您提供了一些功能(例如縮放)。

爲了完成這項工作,您還需要Android Manifest中的'Google API'庫,並且需要Internet-Permission(以獲取卡)。您應該閱讀this tutorial關於如何正確完成所有內容。

2

您需要添加的權限android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATION使用GPS清單檔案中的