2017-07-25 2 views
-2

Je ne parviens pas à obtenir l'emplacement actuel dès que j'ouvre mon activité Maps. Bien qu'il affiche l'emplacement actuel avec la marque de point bleu.Impossible d'obtenir l'emplacement actuel dès que j'ouvre mon activité Maps

Je vois un message d'exception: java.lang.NullPointerException: tentative d'invoquer la méthode virtuelle « double android.location.Location.getLatitude() » sur une référence d'objet nul

Il faut beaucoup de temps iront chercher coordonnées. Pour cela, je dois déplacer mon téléphone et attendre.

Voici mon code pour elle:

if (Build.VERSION.SDK_INT < 25) { 
     if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) { 
      // Ask for permission 

      ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
      if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED){ 
       ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
      } 

     } else { 


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
0, locationListener); 

      lastKnownLocation = 
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
try { 
pDialog.hide(); 
locate = new LatLng(lastKnownLocation.getLatitude(), 
lastKnownLocation.getLongitude()); 

mMap.clear(); 
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13)); 
originMarkers.add(mMap.addMarker(new MarkerOptions() 
     .title("Your Location") 
     .position(locate))); 

origin_lati = "" + lastKnownLocation.getLatitude(); 
origin_longi = "" + lastKnownLocation.getLongitude(); 

Log.e("Lati Longi", origin_lati+", "+origin_longi); 
}catch (Exception e){ 
Log.e("Exception", e.toString()); 
} 

     } 
    } 
+2

pourquoi n'utilisez-vous pas le nouveau fusedLocationApi pour les mises à jour de localisation ?? – sumit

+0

Je suis assez nouveau à ce concept. Comment cela marche-t-il? –

+0

Dois-je changer le code complet? –

Répondre

0

Utilisez ceci:

d'abord créer le client Google Api:

/** 
    * Builds a GoogleApiClient. 
    * Uses the addApi() method to request the Google Places API and the Fused Location Provider. 
    */ 
    private synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this /* FragmentActivity */, 
         this /* OnConnectionFailedListener */) 
       .addConnectionCallbacks(this) 
       .addApi(LocationServices.API) 
       .addApi(Places.GEO_DATA_API) 
       .addApi(Places.PLACE_DETECTION_API) 
       .build(); 
     createLocationRequest(); 
    } 

/** 
    * Sets up the location request. 
    */ 
    private void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 

     /* 
     * Sets the desired interval for active location updates. This interval is 
     * inexact. You may not receive updates at all if no location sources are available, or 
     * you may receive them slower than requested. You may also receive updates faster than 
     * requested if other applications are requesting location at a faster interval. 
     */ 
     mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 

     /* 
     * Sets the fastest rate for active location updates. This interval is exact, and your 
     * application will never receive updates faster than this value. 
     */ 
     mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 

     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 

alors obtenir l'emplacement:

/** 
    * Gets the current location of the device and starts the location update notifications. 
    */ 
    private void getDeviceLocation() { 
     /* 
     * Request location permission, so that we can get the location of the 
     * device. The result of the permission request is handled by a callback, 
     * onRequestPermissionsResult. 
     */ 
     if (ContextCompat.checkSelfPermission(this.getApplicationContext(), 
       android.Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      mLocationPermissionGranted = true; 
     } else { 
      ActivityCompat.requestPermissions(this, 
        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
        PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); 
     } 
     /* 
     * Get the best and most recent location of the device, which may be null in rare 
     * cases when a location is not available. 
     * Also request regular updates about the device location. 
     */ 
     if (mLocationPermissionGranted) { 
      mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, 
        mLocationRequest, this); 
     } 
    } 



/** 
    * Handles the result of the request for location permissions. 
    */ 
    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              @NonNull String permissions[], 
              @NonNull int[] grantResults) { 
     mLocationPermissionGranted = false; 
     switch (requestCode) { 
      case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        mLocationPermissionGranted = true; 
       } 
      } 
     } 
    } 

Maintenant mCurrentLocation a y notre emplacement actuel l'utilise où vous voulez.

construire le client api de votre onCreate:

// Build the Play services client for use by the Fused Location Provider and the Places API. 
     buildGoogleApiClient(); 
     mGoogleApiClient.connect(); 

puis à l'intérieur de votre onResume:

@Override 
    protected void onResume() { 
     super.onResume(); 
     if (mGoogleApiClient.isConnected()) { 
      getDeviceLocation(); 
     } 
    } 

Declare suivant les variables globales:

// The entry point to Google Play services, used by the Places API and Fused Location Provider. 
    private GoogleApiClient mGoogleApiClient; 
    // A request object to store parameters for requests to the FusedLocationProviderApi. 
    private LocationRequest mLocationRequest; 
    // The desired interval for location updates. Inexact. Updates may be more or less frequent. 
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; 
    // The fastest rate for active location updates. Exact. Updates will never be more frequent 
    // than this value. 
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 
      UPDATE_INTERVAL_IN_MILLISECONDS/2; 
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; 
    private boolean mLocationPermissionGranted; 

    // The geographical location where the device is currently located. 
    private Location mCurrentLocation; 
0

J'ai obtenu ma solution avec juste une légère modification

String provider; 
    provider=locationManager.getProvider(LocationManager.NETWORK_PROVIDER).getName(); 

      if (Looper.myLooper() == null) { 
       Looper.prepare(); 
      } 

      locationManager.requestSingleUpdate(provider, locationListener, Looper.myLooper()); 

      locationManager.requestLocationUpdates(provider,0,0, locationListener); 

      currentLocation = locationManager.getLastKnownLocation(provider); 
try { 
pDialog.hide();                      
locate = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); 

mMap.clear(); 
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13)); 
originMarkers.add(mMap.addMarker(new MarkerOptions() 
     .title("Your Location") 
     .position(locate))); 

origin_lati = "" + currentLocation.getLatitude(); 
origin_longi = "" + currentLocation.getLongitude(); 

Log.e("Lati Longi", origin_lati+", "+origin_longi); 
}catch (Exception e){ 
ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
Log.e("Exception", e.toString()); 
}