1

我要去的地圖,以顯示用戶當前位置的用戶currentLocation但我已經在的onResume()以下錯誤(super.onResume()):不能得到Android的

@Override 
    public void onResume() { 
     **super.onResume();** 
     mapView.onResume(); 
     mGoogleApiClient.connect(); 
    } 
    java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.maps.api.android.lib6.d.fk.o()' on a null object reference 

我的類繼承了以下內容:

extends SupportMapFragment implements 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener,LocationListener 

onCreateView:

mapView=(MapView)view.findViewById(R.id.map); 
     mapView.onCreate(savedInstanceState); 

     map = mapView.getMap(); 
     mGoogleApiClient = new GoogleApiClient.Builder(mActivity) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
     mLocationRequest = LocationRequest.create() 
       .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) 
       .setInterval(10 * 1000)  // 10 seconds, in milliseconds 
       .setFastestInterval(1 * 1000); // 1 second, in milliseconds 

覆蓋:

@Override 
    public void onConnected(Bundle bundle) { 
     Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
     if (location == null) { 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 
     } 
     else { 
      handleNewLocation(location); 
     }; 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 


    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     if (connectionResult.hasResolution()) { 
      try { 
       // Start an Activity that tries to resolve the error 
       connectionResult.startResolutionForResult(mActivity, CONNECTION_FAILURE_RESOLUTION_REQUEST); 
      } catch (IntentSender.SendIntentException e) { 
       e.printStackTrace(); 
      } 
     } else { 
      Log.i("TAG", "Location services connection failed with code " + connectionResult.getErrorCode()); 
     } 
    } 
    private void handleNewLocation(Location location) { 
     double currentLatitude = location.getLatitude(); 
     double currentLongitude = location.getLongitude(); 
     LatLng latLng = new LatLng(currentLatitude, currentLongitude); 
     MarkerOptions options = new MarkerOptions() 
       .position(latLng) 
       .title("I am here!"); 
     map.addMarker(options); 
     map.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
    } 
@Override 
    public void onLocationChanged(Location location) { 
     handleNewLocation(location); 
    } 

我真的不知道這個錯誤,請幫幫我。

回答

0

添加到您的onCreateView ()

super.onCreateView(inflater, container, savedInstanceState);

您的onCreateView()沒有它是沒用的。這就是您的mapView.onCreate(savedInstanceState);未被調用的原因。

確保您初始化您的mapView對象(new MapView),它可能爲空。

+0

非常感謝你,你救了我 – samira

0

我建議你使用外部文件來獲取你的位置,這裏是代碼。

package com.appadeus.homer.utilities; 

import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

import com.mapbox.mapboxsdk.geometry.LatLng; 

public class GPSTracker extends Service implements LocationListener { 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 
    public boolean isLocationAlertShown = true; 
    public boolean comeBackAfterTurnGPSON = false; 


    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

    public GPSTracker(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 

      } else { 
       this.canGetLocation = true; 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 

          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 

    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app 
    * */ 
    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(GPSTracker.this); 
     }  
    } 

    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 
    /* 
    * function to return LatLng 
    */ 
    public LatLng getLatLng() { 
     LatLng newLatLng = null; 
     if(location!=null) 
     { 
      newLatLng = new LatLng(location.getLatitude(), location.getLongitude()); 
      return newLatLng; 
     } 
     return newLatLng; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    * */ 
    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 
     alertDialog.setCancelable(true); 

     // Setting Dialog Title 
     //  alertDialog. 

     // Setting Dialog Message 
     alertDialog.setMessage("Please Turn on Location Services"); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
       comeBackAfterTurnGPSON = true; 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     this.location = location; 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

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

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

} 

在第一intilalize侑對象由

GPSTracker gps = new GPSTracker(context); 

,並使用它首先,你應該檢查是否啓用了GPS或不按呼叫

if(gps.canGetLocation()) 
{ 
    //add your code here 
    gps.getLocation() 
} 
else 
{ 
    //show allert dialog to open setting 
    gps.showSettingsAlert(); 
}