1

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?

bigstones
  • 15,087
  • 7
  • 65
  • 82
4af2e9eb6
  • 682
  • 3
  • 7
  • 20
  • could you provide log of the error ? – darune May 20 '11 at 12:27
  • 2
    Where is `updateWithNewLocation()` defined? You don't show it anywhere in your code. Also, what is the error you receive in LogCat? – Kevin Coppock May 20 '11 at 12:28
  • I mean the updateWithNewLocation() is outside just below the onCreate() method. It has been defined there. I simply wonder why it cannot be called inside the onCreate() method. Thanks! – 4af2e9eb6 May 20 '11 at 12:40

1 Answers1

0

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, because location is probably null. It may take seconds to minutes before you will have a location after calling requestLocationUpdates(). If this indeed is what you are encountering, modify your application to remove the getLastKnownLocation() call and move your updateWithNewLocation() call to the onLocationChange() method in MyLocationUpdater.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you very much!! The message in the log is the NullPointerException! Actually it is the part of my problem, would you love to help me to solve the whole problem? Here is the link. http://stackoverflow.com/questions/6068614/get-gps-location-instantly-via-android-app – 4af2e9eb6 May 20 '11 at 12:47
  • @KittenTom: You already have three answers on that question. Two at least seem correct. – CommonsWare May 20 '11 at 12:58