1

having a problem trying to understand how to use a timer in android. I have an activity that sets up a timerTask in my onCreate method. I call the task on a button click and all it is supposed to do is append a textview. The problem is that I am getting a NullPointerException at timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);

is there any obvious reason for this that I am missing?

public class UseGps extends Activity
{

    Button gps_button;
    TextView gps_text;
    LocationManager mlocManager;
    TimerTask task;
    Timer timer;
    public final int TIMER_DELAY = 1000;
    public final int TIMER_ONE_MINUTE = 60000; 
    public final int TIMER_ONE_SECOND = 1000;

public void onCreate(Bundle savedInstanceState)

        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            gps_button = (Button) findViewById(R.id.Button);
            gps_text = (TextView) findViewById(R.id.Text);

            task = new TimerTask() {            
                @Override
                public void run() {
                    gps_text.append("Time up ");
                    try {
                        this.wait(TIMER_DELAY);
                    }
                    catch (InterruptedException e){
                    }
                }

            };

            /* Use the LocationManager class to obtain GPS locations */

            double gps[] = getLastKnownGPS();
            gps_text.setText("Last known Location = "+gps[0]+"   "+gps[1]);


            gps_button.setOnClickListener(new OnClickListener() {
                public void onClick(View viewParam){
                    gps_text.append("\n\nSearching for current location. Please hold...");
                    gps_button.setEnabled(false);
                    mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
                    LocationListener mlocListener = new MyLocationListener();
                    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

                    timer.schedule(task, TIMER_DELAY, 3*TIMER_ONE_SECOND);

                }
            });

        }
}

Thanks in advance

Kevin

Kevin Bradshaw
  • 6,327
  • 13
  • 55
  • 78
  • sorry, not sure what you mean, can you expand? thanks – Kevin Bradshaw Aug 12 '10 at 22:27
  • Sure. In your code snippet you have a reference: Timer timer; But never allocate an instance by calling timer = new Timer(); Please see example for details – Asahi Aug 12 '10 at 22:33
  • Thanks Asahi, I see it now. Thanks for your advice. although I thought I was allocating it with the line: task = new TimerTask() – Kevin Bradshaw Aug 12 '10 at 22:41

0 Answers0