2016-05-03 50 views
0

我每次運行它,我得到這個錯誤信息「java.lang.IllegalStateException:之前的onCreate系統不可用活動服務()」讓用戶地理定位API 23

我需要得到用戶的經度和因此我可以將其用於我的應用程序的其餘部分,但我無法弄清楚如何克服此錯誤。

public class map extends FragmentActivity implements OnMapReadyCallback { 

private GoogleMap mMap; 
private FloatingActionButton plus; 
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
double longitude = location.getLongitude(); 
double latitude = location.getLatitude(); 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_map); 

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

    plus = (FloatingActionButton) findViewById(R.id.newPlace); 

    plus.setOnClickListener(new View.OnClickListener(){ 
     @Override 
     public void onClick(View v) { 
      startActivity(new Intent(map.this, newPlacePop.class)); 
     } 
    }); 
} 



@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 

    LatLng currentPosition = new LatLng(latitude, longitude); 

    float zoomLevel = 16; //This goes up to 21 
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, zoomLevel)); 

} 

}

回答

1
java.lang.IllegalStateException: System services not available to Activities before onCreate() 

您有調用getSystemService()場初始化:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

不能調用getSystemService() —或大多數其他方法,您是從Activity —繼承前以onCreate()方式致電super.onCreate() OD。

所以,變化:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
double longitude = location.getLongitude(); 
double latitude = location.getLatitude(); 

到:

LocationManager lm; 
Location location; 
double longitude; 
double latitude; 

,並添加super.onCreate()後以下行你onCreate()方法:

lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 

if (location==null) { 
    // do something 
} 
else { 
    longitude = location.getLongitude(); 
    latitude = location.getLatitude(); 
} 

我需要得到我用戶的經度和緯度可以用於我的應用程序的其餘部分

您的代碼不太可能獲得經度和緯度。 getLastKnownLocation()經常返回null,如果沒有if檢查上面顯示的代碼,你會崩潰NullPointerException。您不妨閱讀the documentation on getting location data

此外,你提到「API 23」。如果您的targetSdkVersion爲23或更高,則需要the code to request your location permission at runtime