在getLatitude空指针异常 [英] Null Pointer Exception on getLatitude

查看:278
本文介绍了在getLatitude空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

双android.location.Location.getLatitude()在空对象引用

 返回新ParseGeoPoint(loc.getLatitude(),loc.getLongitude());

和与ParseGeoQuery

  query.whereWithinKilometers(GeoArea,geoPointFromLocation(myLoc),半径);

这是onCreate方法所在的位置被初始化

  //创建一个新的全球定位参数对象
        locationRequest = LocationRequest.create();        //设置更新间隔
        locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);        //使用精度高
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);        //区间上限设置为一分钟
        locationRequest.setFastestInterval(FAST_INTERVAL_CEILING_IN_MILLISECONDS);        //创建一个新的位置客户端,使用封闭的类来处理回调。
        locationClient =新GoogleApiClient.Builder(本)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(本)
                .addOnConnectionFailedListener(本)
                。建立();

这是我的ParseQuery进行地理定位。

  @覆盖
    公共无效调用onStart(){
        super.onStart();        //连接到位置服务客户端
        locationClient.connect();
    }
     FiltersQueryAdapter mainAdapter =新FiltersQueryAdapter(这一点,PhotoFiltersAdapter.class
                ,新ParseRecyclerQueryAdapter.QueryFactory(){
            公共ParseQuery创建(){
                位置myLoc =(currentLocation == NULL)? lastLocation:currentLocation;
                ParseQuery查询= ParseQuery.getQuery(PlaceFilters);
                //query.include(\"user);
                query.orderByAscending(GeoArea);
                query.whereWithinKilometers(GeoArea,geoPointFromLocation(myLoc),半径);
                query.setLimit(6);
                返回查询;
            }
        });     @覆盖
        保护无效onResume(){
            super.onResume();
            cameraView.onResume();            //获取最新的搜索距离preference
            半径= InstaMaterialApplication.getSearchDistance();
            //检查上次保存的位置,以显示缓存的数据(如果可用)
            如果(lastLocation!= NULL){
                //如果搜索距离preference已经改变,移动
                //映射到新范围。
                如果(lastRadius!=半径){
                    //保存当前半径
                    lastRadius =半径;
                    doListQuery();
                }
            }
        }        公共无效onConnected(束束){
                如果(InstaMaterialApplication.APPDEBUG){
                    Log.d(位置连接,InstaMaterialApplication.APPTAG);
                }
                currentLocation =的getLocation();
                startPeriodicUpdates();
            }          公共无效onLocationChanged(地点){
                currentLocation =位置;
                如果(lastLocation!= NULL
                            &功放;&安培; geoPointFromLocation(位置)
                            .distanceInKilometersTo(geoPointFromLocation(lastLocation))≤; 0.01)
                {
                    //如果位置已不超过10米改变,忽略它。
                    返回;
                }
                lastLocation =位置;                如果(!hasSetUpInitialLocation){
                    hasSetUpInitialLocation = TRUE;
                }
                //更新地图半径指标
                doListQuery();
            }            / *
           *为应对开始更新的请求,发送到位置服务的请求
           * /
            私人无效startPeriodicUpdates(){
                如果(ActivityCompat.checkSelfPermission(这一点,Manifest.permission.ACCESS_FINE_LOCATION)= PackageManager.PERMISSION_GRANTED和放大器;!&安培;!ActivityCompat.checkSelfPermission(这一点,Manifest.permission.ACCESS_COARSE_LOCATION)= PackageManager.PERMISSION_GRANTED){
                    // TODO:考虑调用
                    // ActivityCompat#requestPermissions
                    //这里索取缺少的权限,然后覆盖
                    //公共无效onRequestPermissionsResult(INT申请code,的String []的权限,
                    // INT [] grantResults)
                    //处理,其中用户授予权限的情况。查看文档
                    //为ActivityCompat#requestPermissions了解更多详情。
                    返回;
                }
                LocationServices.FusedLocationApi.requestLocationUpdates(
                        locationClient,locationRequest,这一点);
            }            / *
             *在响应请求停止更新,发送到位置服务的请求
             * /
            私人无效stopPeriodicUpdates(){
                locationClient.disconnect();
            }            / *
           *获取当前位置
           * /
            私人位置的getLocation(){
                //如果谷歌播放服务提供
                如果(servicesConnected()){
                    //获取当前位置
                    如果(ActivityCompat.checkSelfPermission(这一点,Manifest.permission.ACCESS_FINE_LOCATION)= PackageManager.PERMISSION_GRANTED和放大器;!&安培;!ActivityCompat.checkSelfPermission(这一点,Manifest.permission.ACCESS_COARSE_LOCATION)= PackageManager.PERMISSION_GRANTED){
                        // TODO:考虑调用
                        // ActivityCompat#requestPermissions
                        //这里索取缺少的权限,然后覆盖
                        //公共无效onRequestPermissionsResult(INT申请code,的String []的权限,
                        // INT [] grantResults)
                        //处理,其中用户授予权限的情况。查看文档
                        //为ActivityCompat#requestPermissions了解更多详情。
                    }
                    返回LocationServices.FusedLocationApi.getLastLocation(locationClient);
                }其他{
                    返回null;
                }
            }            / *
           *设置一个查询来更新列表视图
           * /
            私人无效doListQuery(){
                位置myLoc =(currentLocation == NULL)? lastLocation:currentLocation;
                //如果位置信息可用,加载数据
            }            / *
           *辅助方法来获得一个位置的解析GEO点重新presentation
           * /
            私人ParseGeoPoint geoPointFromLocation(位置LOC){
                返回新ParseGeoPoint(loc.getLatitude(),loc.getLongitude());
            }

我的舱单的权限来访问谷歌播放服务和位置

 <使用许可权的android:NAME =android.permission.ACCESS_FINE_LOCATION/>
    <使用许可权的android:NAME =android.permission.INTERNET对/>
    <使用许可权的android:NAME =android.permission.CAMERA/>
    <使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAG​​E/>
    <使用许可权的android:NAME =android.permission.ACCESS_NETWORK_STATE/>
    <使用许可权的android:NAME =com.google.android.providers.gsf.permission.READ_GSERVICES/>


解决方案

添加按照您的清单另一种权限

 <使用许可权的android:NAME =android.permission.ACCESS_COARSE_LOCATION/>

我知道你正在使用ACCESS_FINE_LOCATION,但如果GPS信号丢失,并尝试获取经纬度长什么。在这种情况下,你会得到空数据。为了避免这种情况最好是有另一种选择从网络提供商有位置,尽管它可能不准确。

请确保您googleApiClient与你的客户建设者在此之后的呼叫建立连接。

  //创建一个新的位置客户端,使用封闭的类来处理回调。
        locationClient =新GoogleApiClient.Builder(本)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(本)
                .addOnConnectionFailedListener(本)
                。建立();locationClient.connect();

'double android.location.Location.getLatitude()' on a null object reference

 return new ParseGeoPoint(loc.getLatitude(), loc.getLongitude());

and with the ParseGeoQuery

query.whereWithinKilometers("GeoArea", geoPointFromLocation(myLoc), radius);

This is the onCreate Method where the location is being initialized

   // 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();

This is my ParseQuery for GeoLocation

@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());
            }

My Manifest Permissions to access Google Play Services and Location

<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" />

解决方案

Add following another permission in your manifest

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

I know you are using ACCESS_FINE_LOCATION, but what if you lost GPS signal and try to get lat long. In this scenario you will get null data. To avoid such situation better to have another option to have location from Network Provider though it may not be accurate.

Make sure to connect your googleApiClient with this call after your client builder.

// 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();

这篇关于在getLatitude空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆