getLatitude 上的空指针异常
Posted
技术标签:
【中文标题】getLatitude 上的空指针异常【英文标题】:Null Pointer Exception on getLatitude 【发布时间】:2016-02-17 10:31:23 【问题描述】:空对象引用上的'double android.location.Location.getLatitude()'
return new ParseGeoPoint(loc.getLatitude(), loc.getLongitude());
并使用 ParseGeoQuery
query.whereWithinKilometers("GeoArea", geoPointFromLocation(myLoc), radius);
这是初始化位置的onCreate方法
// Create a new global location parameters object
locationRequest = LocationRequest.create();
// Set the update interval
locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
locationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Create a new location client, using the enclosing class to handle callbacks.
locationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
这是我对 GeoLocation 的 ParseQuery
@Override
public void onStart()
super.onStart();
// Connect to the location services client
locationClient.connect();
FiltersQueryAdapter mainAdapter = new FiltersQueryAdapter(this, PhotoFiltersAdapter.class
, new ParseRecyclerQueryAdapter.QueryFactory()
public ParseQuery create()
Location myLoc = (currentLocation == null) ? lastLocation : currentLocation;
ParseQuery query = ParseQuery.getQuery("PlaceFilters");
//query.include("user");
query.orderByAscending("GeoArea");
query.whereWithinKilometers("GeoArea", geoPointFromLocation(myLoc), radius);
query.setLimit(6);
return query;
);
@Override
protected void onResume()
super.onResume();
cameraView.onResume();
// Get the latest search distance preference
radius = InstaMaterialApplication.getSearchDistance();
// Checks the last saved location to show cached data if it's available
if (lastLocation != null)
// If the search distance preference has been changed, move
// map to new bounds.
if (lastRadius != radius)
// Save the current radius
lastRadius = radius;
doListQuery();
public void onConnected(Bundle bundle)
if (InstaMaterialApplication.APPDEBUG)
Log.d("Location Connected", InstaMaterialApplication.APPTAG);
currentLocation = getLocation();
startPeriodicUpdates();
public void onLocationChanged(Location location)
currentLocation = location;
if (lastLocation != null
&& geoPointFromLocation(location)
.distanceInKilometersTo(geoPointFromLocation(lastLocation)) < 0.01)
// If the location hasn't changed by more than 10 meters, ignore it.
return;
lastLocation = location;
if (!hasSetUpInitialLocation)
hasSetUpInitialLocation = true;
// Update map radius indicator
doListQuery();
/*
* In response to a request to start updates, send a request to Location Services
*/
private void startPeriodicUpdates()
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
LocationServices.FusedLocationApi.requestLocationUpdates(
locationClient, locationRequest, this);
/*
* In response to a request to stop updates, send a request to Location Services
*/
private void stopPeriodicUpdates()
locationClient.disconnect();
/*
* Get the current location
*/
private Location getLocation()
// If Google Play Services is available
if (servicesConnected())
// Get the current location
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return LocationServices.FusedLocationApi.getLastLocation(locationClient);
else
return null;
/*
* Set up a query to update the list view
*/
private void doListQuery()
Location myLoc = (currentLocation == null) ? lastLocation : currentLocation;
// If location info is available, load the data
/*
* Helper method to get the Parse GEO point representation of a location
*/
private ParseGeoPoint geoPointFromLocation(Location loc)
return new ParseGeoPoint(loc.getLatitude(), loc.getLongitude());
我的清单访问 Google Play 服务和位置的权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
【问题讨论】:
loc的值必须为null(它必须没有任何值) 除了 ParseGeoPoint GeoPointfromLocation 之外,我没有在其他地方将其称为 getLatitude @saeed 我应该添加这个双纬度 = location.getLatitude();低于 lastLocation = 位置 @saeed 我在 loc.getLatitude 上获得 Null 并获得 loc.getLongitude,因为我已将其发布在我的帖子顶部。您还可以在 ParseGeoQuery 部分找到它吗?它已发布在底部 What is a Null Pointer Exception, and how do I fix it?的可能重复 【参考方案1】:在您的清单中添加以下另一个权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
我知道您正在使用 ACCESS_FINE_LOCATION,但是如果您丢失 GPS 信号并尝试获得更长的纬度怎么办。在这种情况下,您将获得空数据。为了避免这种情况,最好有另一种选择从网络提供商那里获得位置,尽管它可能不准确。
确保在您的客户端构建器之后将您的 googleApiClient 与此调用连接起来。
// Create a new location client, using the enclosing class to handle callbacks.
locationClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
locationClient.connect();
【讨论】:
仍然返回空指针异常 检查您的客户端是否已连接。如果没有,请致电 locationClient.connect(); 应该将 locationCLient.connect() 传递到哪里? 已更新答案 - 在 onCreate 中的客户端构建器之后 我在 @Override onStart() 中有 locationClient.connect()以上是关于getLatitude 上的空指针异常的主要内容,如果未能解决你的问题,请参考以下文章
OnGridImageSelectedListener.onGridImageSelected 上的空指针异常