MapsActivity在加载

时间:2017-03-14 12:19:45

标签: java android

嘿,我是Android的新手,想知道是否有人可以帮助我。我有一个MapsActivity,当导航到它时会崩溃。我认为我已经缩小到了查看错误的确切位置,但我无法弄清楚要改变什么。 我在下面添加了整个MapsActivity类。问题出现在此行mLocationManager.requestLocationUpdates(provider, 5000, 0, this); 上的onConnected方法中。 Android Studio建议我投射这个'到LocationListener,但这不起作用,我这样做的错误列在MapsActivity代码下面。 我也尝试输入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错误 -

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)

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您的requestLocationUpdates找不到监听器的实例,因此将MapsActivity.this添加到requestLocationUpdates

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mLocationManager.requestLocationUpdates(provider, 5000, 0, MapsActivity.this);//Changed here
            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);
        }

答案 2 :(得分:0)

对于第一次崩溃:由于您对Activity实施的位置侦听器类的导入不正确而导致此崩溃。

使用com.google.android.gms.location.LocationListener

更改android.location.LocationListener

并且对于第二次崩溃使用下面的LocationListener,由于您对位置侦听器对象的空引用而发生此崩溃。

 private LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};