2014-07-27 47 views
4

我正在嘗試製作顯示設備當前(或最後已知位置)的Android應用程序。 這是在logcat中所示的錯誤:嘗試調用虛擬方法。應用程序顯示位置

07-27 14:47:53.766:E/AndroidRuntime(28080): 顯示java.lang.NullPointerException:致嘗試調用虛擬方法 '雙android.location.Location.getLatitude()」空對象 參考

這是我的Java代碼:

package com.example.autosilence; 

import android.app.Activity; 
import android.content.Context; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.view.Menu; 
import android.widget.TextView; 

public class MainActivity extends Activity { 

    TextView lat = (TextView)findViewById(R.id.lat); 
    TextView lon = (TextView)findViewById(R.id.lon); 
    int b,c; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

     Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if (lastLocation != null) 
     { 
      lat.setText(Double.toString(lastLocation.getLatitude())); 
      lon.setText(Double.toString(lastLocation.getLongitude())); 
     } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

} 

我已經允許permissio ns用於Android清單中的精細和粗略位置。 這是怎麼回事?

回答

1

這可能無法解決問題,但您在佈局膨脹之前發現視圖。移動

TextView lat = (TextView)findViewById(R.id.lat); 
TextView lon = (TextView)findViewById(R.id.lon); 

onCreate裏面,setContentView()後。

+0

是的,你當然是對的! 但是這並沒有清除其他問題。不管怎麼說,還是要謝謝你! – user3430238

1

您是使用模擬器還是設備來測試您的代碼?

仿真程序無法檢測到您的當前位置,因爲系統不包含GPS,所以在初始化程序中返回null。所以它返回一個nullPointerException。在運行位置服務代碼之前,您需要在模擬器中配置GPS設置,或嘗試在設備上運行它。

相關問題