2017-07-25 4 views
-2

Ich kann den aktuellen Standort nicht abrufen, sobald ich meine Google Maps-Aktivität öffne. Obwohl es die aktuelle Position mit der blauen Punktmarkierung anzeigt.Ich kann den aktuellen Standort nicht abrufen, sobald ich meine Google Maps-Aktivität öffne

Ich sehe eine Ausnahmemeldung: java.lang.NullPointerException: Der Versuch, virtuelle Methode ‚double android.location.Location.getLatitude()‘ auf ein Null-Objekt Verweis aufrufen

es viel Zeit in Anspruch nimmt zu holen Koordinaten. Dafür muss ich mein Handy bewegen und warten.

Hier ist mein Code dafür:

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

Warum verwenden Sie den neuen fusionLocationApi nicht für Standortaktualisierungen? – sumit

+0

Ich bin ziemlich neu in diesem Konzept. Wie funktioniert das? –

+0

Muss ich den kompletten Code ändern? –

Antwort

0

verwenden:

Erstes Google-API-Client erstellen:

/** 
    * 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); 
    } 

dann Standort zu erhalten:

/** 
    * 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; 
       } 
      } 
     } 
    } 

Jetzt hat mCurrentLocation y unser aktueller Standort nutzen Sie, wo immer Sie wollen.

build der Api-Client von Ihrem onCreate:

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

und dann in Ihrem onResume:

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

Declare folgende globale Variablen:

// 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

ich nur meine Lösung bekam eine geringfügige Änderung

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()); 
} 
Verwandte Themen