2012-10-04 45 views
0

你好,我想獲得精確的位置,這樣我已經使用下面的鏈接致命異常:定時器0

What is the simplest and most robust way to get the user's current location in Android?

下面

是從該網站的代碼:

 LocationResult locationResult = new LocationResult(){ 
    @Override 
    public void gotLocation(Location location){ 
     //Got the location! 
    } 
    }; 

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

現在LocationResult我修改了它,並希望顯示LOCATION的文本視圖 ,所以我寫下面的代碼

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    LocationResult locationResult = new LocationResult(){ 
     @Override 
     public void gotLocation(Location location){ 
      TextView txtValue = (TextView)findViewById(R.id.txtValue); 
      txtValue.setText("LATITUDE : - "+location.getLatitude()+"\n\n LONGITUDE :- "+location.getLongitude()+"\n\n ALTITUDE :- "+location.getAltitude()); 
     } 
    }; 
    myLocation = new MyLocation(); 
    myLocation.getLocation(this, locationResult); 

} 

但在我得到像

下面

的例外是我的logcat

10-04 17:06:35.699: E/AndroidRuntime(5733): FATAL EXCEPTION: Timer-0 
10-04 17:06:35.699: E/AndroidRuntime(5733): java.lang.NullPointerException 
10-04 17:06:35.699: E/AndroidRuntime(5733): at com.example.gps_accurate_data.MainActivity$1.gotLocation(MainActivity.java:22) 
10-04 17:06:35.699: E/AndroidRuntime(5733): at com.example.gps_accurate_data.MyLocation$GetLastLocation.run(MyLocation.java:119) 
10-04 17:06:35.699: E/AndroidRuntime(5733): at java.util.Timer$TimerImpl.run(Timer.java:284) 

回答

1

如果你看看你提供的鏈接,當設備h試圖獲取位置,它會運行代碼;

if(gps_loc!=null){ 
    locationResult.gotLocation(gps_loc); 
    return; 
} 

if(net_loc!=null){ 
    locationResult.gotLocation(net_loc); 
    return; 
} 

locationResult.gotLocation(null); 

這意味着,如果它不能得到定位它很可能打電話給你設置爲null的位置。你需要檢查。

0

在頂部中聲明你的活動:TextView txtValue;

然後在您的onCreate()txtValue = (TextView)findViewById(R.id.txtValue);

if(location != null){ 
    txtValue.setText("LATITUDE : - "+location.getLatitude()+"\n\n LONGITUDE :- "+location.getLongitude()+"\n\n ALTITUDE :- "+location.getAltitude()); 
} 
+0

不,這不是一個問題! –

+0

你在MainActivity的第22行有什麼? – Carnal

+0

txtValue.setText(「LATITUDE: - 」+ location.getLatitude()+「\ n \ n LONGITUDE: - 」+ location.getLongitude()+「\ n \ n ALTITUDE: - 」+ location.getAltitude()); –