2016-05-03 51 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