2014-07-27 49 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设置,或尝试在设备上运行它。

相关问题