我正在测试一个使用Location服务的应用程序。当我的位置服务被关闭时,它返回null,导致NPE (Null Pointer Exception)。所以经过一番搜索,我发现
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);应该返回正确的boolean value,但在测试我的应用程序时,它似乎总是返回true,导致NPE (Null Pointer Exception)和应用程序崩溃。
我也读过this的问题。显然有完全相反的问题,并尝试了这个解决方案。这也没用。我正在三星G5上进行测试。为什么会发生这种事。是代码有问题还是我的问题有其他解决方案。
以下是代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isGPSEnabled = false;
intentThatCalled = getIntent();
String m2txt = intentThatCalled.getStringExtra("v2txt");
getLocation(m2txt);
}
public void getLocation(String n2txt) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
location = locationManager.getLastKnownLocation(bestProvider);
isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
if (isGPSEnabled==true) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(PlacesDecoder.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(n2txt);
}
}我仍然是android系统的初学者。请帮帮忙。
编辑:在相同的硬件模型上, This问题似乎有相同的问题。这是硬件故障吗?如果是的话,还有其他的可能性吗?我也会测试另一个设备说明-4,并让你知道。
发布于 2015-08-29 12:49:55
您的问题的解决方案是从不假设您有一个位置,仅仅因为您的GPS已启用并不意味着您将得到一个位置。
在任何时候,您都可以得到一个null位置,所以不必担心是否启用了GPS,而应该担心您返回的位置是否为空。
如果没有最后一个位置,getLastKnownLocation()可以返回null
https://stackoverflow.com/questions/32286193
复制相似问题