java - MapsActivity 加载时崩溃

标签 java android

嘿,我是 Android 新手,想知道是否有人可以帮助我。我有一个 MapsActivity,导航到它时会崩溃。我想我已经通过查看错误缩小了范围,但我不知道要更改什么。 我在下面添加了整个 MapsActivity 类。问题发生在这一行的 onConnected 方法中 mLocationManager.requestLocationUpdates(provider, 5000, 0, this); 。 Android Studio 建议我将“this”转换为 LocationListener,但这不起作用,并且我这样做所得到的错误列在 MapsActivity 代码下方。 我还尝试在“this”的位置输入mLocationListener,但不起作用,并且我也收到了下面列出的错误。

非常感谢任何帮助。谢谢!

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2;
    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private LocationManager mLocationManager;
    private Location mLastLocation;
    private LocationListener mLocationListener;
    private String mLatitude;
    private String mLongitude;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
        //create instance of location manager and get location service
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    @Override
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        mGoogleApiClient.disconnect();
        //mLocationManager.removeUpdates((LocationManager) this);
        super.onStop();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setBearingRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = mLocationManager.getBestProvider(criteria, true);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.requestLocationUpdates(provider, 5000, 0, this);
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if(mLastLocation != null){
                mLatitude = String.valueOf(mLastLocation.getLatitude());
                mLongitude = String.valueOf(mLastLocation.getLongitude());
                Toast.makeText(this, mLatitude + " , " + mLongitude, Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "Permission denied, please accept permission..", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults){
        switch (requestCode){
            case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION:{
                //if request cancelled the results array is empty
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    //do task you wish to do
                    //Intent intent = (new Intent(this, MapsActivity.class));
                    //startActivity(intent);
                }else{
                    //permission denied, disable functionality(GPS)
                }
                return;
            }
            //other cases go here
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }
}

选角错误 -

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.a8460p.locationotes, PID: 23305
              java.lang.ClassCastException: com.example.a8460p.locationotes.MapsActivity cannot be cast to android.location.LocationListener
                  at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
                  at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
                  at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
                  at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
                  at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
                  at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
                  at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
                  at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:234)
                  at android.app.ActivityThread.main(ActivityThread.java:5526)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

用 mLocationListener 错误替换“this” -

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.a8460p.locationotes, PID: 24073
              java.lang.IllegalArgumentException: invalid listener: null
                  at android.location.LocationManager.checkListener(LocationManager.java:1733)
                  at android.location.LocationManager.requestLocationUpdates(LocationManager.java:461)
                  at com.example.a8460p.locationotes.MapsActivity.onConnected(MapsActivity.java:106)
                  at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
                  at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
                  at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
                  at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
                  at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
                  at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
                  at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
                  at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:234)
                  at android.app.ActivityThread.main(ActivityThread.java:5526)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

最佳答案

使 MapsActivity 实现 android.location.LocationListener 而不是 com.google.android.gms.location.LocationListener

关于java - MapsActivity 加载时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42785841/

相关文章:

Java合并排序算法与wait()/notify()同步

java - Android 从图库中选择图像 java.lang.NullPointerException : Attempt to invoke virtual method 'boolean Bitmap.compress()' on a null object

java - Spring Boot Thymeleaf 不加载静态文件

java - 我们如何管理 SMS,哪种语言是最好的处理方式?

java - 比较两个日期是否在android中的同一周内

android - 使用 Espresso 测试可绘制更改

java - 如何优化这个更新 SQL 查询

java - 以批处理模式选择 JDBC SQL

Java Web 服务与 Ksoap2 成功错误错误

Android - 从 keystore 导出单个 key /别名