【发布时间】:2015-05-20 15:07:30
【问题描述】:
我正在尝试向用户邮寄我的经纬度,但我收到了 nullPointerException:
尝试在空对象引用上调用虚拟方法“double android.location.Location.getLatitude()”
我猜 getLastKnownLocation() 方法返回 null 是因为模拟器开始时没有位置?
如果是这样,我该如何以另一种方式做到这一点?
这是我的代码:
public class MainActivity extends Activity {
Button btnSend;
TextView txtview;
String email = "superman@hotmail.com";
String position;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtview = (TextView) findViewById(R.id.textView);
btnSend = (Button) findViewById(R.id.button);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Double lat = location.getLatitude();
Double lng = location.getLongitude();
position = Double.toString(lat + lng);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String[] TO = {"batman@hotmail.com"};
Intent sendMypos = new Intent(Intent.ACTION_SEND);
sendMypos.putExtra(Intent.EXTRA_EMAIL,TO);
sendMypos.putExtra(Intent.EXTRA_SUBJECT,"Min position");
sendMypos.putExtra(Intent.EXTRA_TEXT, position);
sendMypos.setData(Uri.parse("mailto:"));
sendMypos.setType("message/rfc822");
startActivity(Intent.createChooser(sendMypos,"Email klient"));
}
});
}
}
我的清单:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
【问题讨论】:
-
我认为
lm或location是null。我不认为你可以使用模拟器来运行你的代码。您可以用硬编码值替换lat和lng进行测试? -
你需要实现Location Listener
标签: java android android-intent android-studio android-location