【问题标题】:LocationManager returns nullLocationManager 返回空值
【发布时间】:2016-11-16 17:36:17
【问题描述】:

我正在使用 GPS 在 Android 应用中获取我的位置。但是当我创建一个 LocationManager 它返回空指针异常。即使在 androidMainFest.xml 和应用程序上设置了权限,它仍然返回以下异常。谁能提前帮忙。谢谢!

代码:

package com.example.pavsaranga.scat;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class Map extends FragmentActivity implements OnMapReadyCallback, LocationListener {

    private GoogleMap mMap;
    double longitude, latitude;
    String bestProvider;
    LocationManager lm;
    Location location;
    Criteria criteria;
    LocationListener locList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.getUiSettings().setZoomGesturesEnabled(true);
        try {
            boolean permissionGranted = ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
            if (permissionGranted) {
                setMyLocation();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 200);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    private void setMyLocation() {
        try {
            lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(Map.this, "Please Grant Permission.", Toast.LENGTH_SHORT).show();
            } else {
                criteria = new Criteria();
                bestProvider = String.valueOf(lm.getBestProvider(criteria, true)).toString();
                location = lm.getLastKnownLocation(bestProvider);
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                else{
                    lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);
                }
                LatLng myLocation = new LatLng(latitude, longitude);
                mMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here!"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(myLocation));
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 200: {
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Map.this, "Thank You, Permission Granted!.", Toast.LENGTH_SHORT).show();
                    setMyLocation();
                }
            }
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();
    }
}

例外:

java.lang.IllegalArgumentException: invalid listener: null

MainFest.xml

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

【问题讨论】:

  • 你是在硬件设备还是 AVD 上测试这个?
  • 在我的手机上测试过

标签: android locationmanager android-gps


【解决方案1】:

LocationManager 没有返回 null。错误是您传递的是null LocationListener

您需要先初始化loclist,然后再将其传递给requestLocationUpdates

【讨论】:

  • 我没明白,你能告诉我怎么做吗?我是安卓新手
【解决方案2】:

您正在声明 locList 并将其传递给 lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList); 方法。它看起来不像你正在初始化它。 这就是它告诉您的异常,您在期望侦听器的地方传入 null。

您可以删除locList 声明并尝试进行以下更改:

改变

lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);

lm.requestLocationUpdates(bestProvider, 2000, 0, new LocationListener(){
    // @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        /*
        * Called when the provider status changes. 
        * This method is called when a provider is unable to fetch a location 
        * or if the provider has recently become available after a period of unavailability.
        */
    }

    // @Override
    public void onLocationChanged(Location location) {
        /*
        * Called when the location has changed. 
        */
    }
});

【讨论】:

  • 我没明白,你能告诉我怎么做吗?我是安卓新手
  • @VimukthiSaranga 我为你添加了一个示例
  • 但是会返回错误,无法保存代码
  • locList = new LocationListener() { @Override public void onLocationChanged(Location location) { latitude = location.getLatitude();经度 = location.getLongitude(); } }; lm.requestLocationUpdates(bestProvider, 2000, 0, (android.location.LocationListener) locList);
  • 我改成上面那样,新的错误java.lang.ClassCastException: com.example.pavsaranga.scat.Map$1 cannot be cast to android.location.LocationListener
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 2012-05-28
  • 2021-07-07
  • 1970-01-01
  • 2011-11-03
  • 1970-01-01
  • 2021-12-21
相关资源
最近更新 更多