Gus
Gus

Reputation: 108

MapsActivity crashing on load

Hey Im new to Android and wondering if someone can help me. I have a MapsActivity which crashes when navigating to it. I think I've narrowed down to exactly where it is from looking through the errors but I cant figure out what to change. I've added the whole MapsActivity class below. The problem is occuring in the onConnected method on this line mLocationManager.requestLocationUpdates(provider, 5000, 0, this); . Android Studio recommends I cast 'this' to LocationListener but this doesn't work and the error I get from doing so is listed below the MapsActivity code. I have also tried entering mLocationListener in the place of 'this' but doesn't work and I get errors which are listed below too.

ANY HELP IS GREATLY APPRECIATED. THANKS!

    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) {

    }
}

Casting errors -

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)

Replacing 'this' with mLocationListener errors -

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)

Upvotes: 0

Views: 79

Answers (3)

Gopal
Gopal

Reputation: 1784

For First crash: this crash is occuring due to the incorrect import for location listener class which you have implements to your Activity.

Change com.google.android.gms.location.LocationListener with android.location.LocationListener

and for second crash use bellow LocationListener, this crash is occuring due your null reference of location listener object.

 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) {

    }
};

Upvotes: 0

Rajesh
Rajesh

Reputation: 2618

Your requestLocationUpdates could not find instance of Listener so add MapsActivity.this to 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);
        }

Upvotes: 0

RadekJ
RadekJ

Reputation: 3043

Make MapsActivity implements android.location.LocationListener instead of com.google.android.gms.location.LocationListener

Upvotes: 1

Related Questions