Question

I'm trying to run code which has TimerTask, but running into some errors. my MainActivity is http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/ and i'm calling a fragment which does some animation which has this Timertask. Everything is working fine, but when I selected different fragment from list item i'm running into TimerTask error.

public class MyTimerTask extends TimerTask {

    @Override
    public void run() {
       while(true)
       {try {
           Thread.sleep(1000);
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                updateTextView();

            }
        });
    }catch (InterruptedException e){
        e.printStackTrace();
    }

    }

 }

Logcat trace:

FATAL EXCEPTION: Timer-0
java.lang.NullPointerException at com.example.Project.HomeAnimation$MyTimerTask.run(HomeAnimation.java:53)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Était-ce utile?

La solution

You need to stop the while loop somehow. Maybe set a class flag to false in onDestroy and the while loop becomes while(flag):

public class MyTimerTask extends TimerTask {

    @Override
    public void run() {
       flag = true;
       while(flag && (getActivity() != null))
       {try {
           Thread.sleep(1000);
        getActivity().runOnUiThread(new Runnable() {

            @Override
            public void run() {
                updateTextView();

            }
        });
    }catch (InterruptedException e){
        e.printStackTrace();
    }

    }

 }

And your onDestroy method would look like:

public void onDestroy() {
    flag = false;
    super.onDestroy();
}

Don't forget to declare the flag in your fragment class:

private boolean flag = false;

Autres conseils

You can use a Handler in combination with a Runnable:

 Handler hander = new Handler();


// Your runnable that will be triggered.
Runnable runnable = new Runnable() {
       public void run() {

           // do stuff

           // post it again
           handler.postDelayed(this, delay);
       }
    };

// Start
hander.post(runnable);


// Stop
handler.removeCallbacks(runnable);

If you are on a fragment, the easiest way is to check if current fragment is visible by calling isVisible() method :

  @Override
    public void run() {
        if (isVisible()) {
            getActivity().runOnUiThread(new Runnable() {
                public void run() {

                   // stuff to do

                }
            });
        }
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top