致命异常:Timer-0

时间:2012-10-04 11:47:16

标签: java android gps

您好我想获得准确的位置,以便我使用以下链接

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班级我修改了它并希望在textview中显示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)

2 个答案:

答案 0 :(得分:1)

如果查看您提供的链接,当设备尝试获取该位置时,它将运行代码;

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

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

locationResult.gotLocation(null);

这意味着如果位置设置为null,它可能会很好地呼叫您,如果它无法获取位置。你需要检查一下。

答案 1 :(得分: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());
}