There is a problem on my Android app. If I put a method inside onCreate(), the whole app will crash.
Here is the code
private LocationManager locationManager = null;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Intent i3 = new Intent();
i3.setClass(mainMenu.this, police.class);
i3.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainMenu.this.startActivityForResult(i3,0);
}
});
locationManager = (LocationManager)mainMenu.this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000 , 0 , new MyLocationUpdater());
Location location = locationManager.getLastKnownLocation(locationManager.GPS_PROVIDER);
updateWithNewLocation(location);
}
The updateWIthNewLocation(Location location) method is outside the onCreate();
I can’t call it successfully inside the onCreate().
Any ideas?
First, you need to learn to use
adb logcat, DDMS, or the DDMS perspective in Eclipse, to examine LogCat and look at the stack trace associated with your error.My guess is that you are crashing with a
NullPointerException, becauselocationis probablynull. It may take seconds to minutes before you will have a location after callingrequestLocationUpdates(). If this indeed is what you are encountering, modify your application to remove thegetLastKnownLocation()call and move yourupdateWithNewLocation()call to theonLocationChange()method inMyLocationUpdater.