androidandroid-fragmentsandroid-timer

TimerTask inside Fagment


Basically, I need to use a TimerTask inside a fragment but this error appears:

04-04 15:01:02.710 28397-28528/com.example.sdilab.pap E/AndroidRuntime: FATAL EXCEPTION: Timer-1
    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5471)
    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1007)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.support.v4.widget.DrawerLayout.requestLayout(DrawerLayout.java:1255)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:334)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:334)
    at android.view.View.requestLayout(View.java:15850)
    at android.view.View.requestLayout(View.java:15850)
    at android.widget.TextView.checkForRelayout(TextView.java:6615)
    at android.widget.TextView.setText(TextView.java:3753)
    at android.widget.TextView.setText(TextView.java:3608)
    at android.widget.TextView.setText(TextView.java:3583)
    at com.example.sdilab.pap.StepsFragment$1.run(StepsFragment.java:87)
    at java.util.Timer$TimerImpl.run(Timer.java:284)

And this is the code that I need to use:

timer.schedule( new TimerTask() {
            public void run() {
                double value = Double.parseDouble(readFromFile());
                String roundedvalue = Math.round(passos) + "";
                textView.setText(roundedvalue);

            }
        }, 0, 1*1000);

My question is: How can I use this code / achieve the same result so I can use this code inside my fragment?


Solution

  • Use runOnUiThread() method to update TextView

    timer.schedule( new TimerTask() {
                    public void run() {
                        double value = Double.parseDouble(readFromFile());
                        String roundedvalue = Math.round(passos) + "";
    
             runOnUiThread(new Runnable() {
                    public void run() {
                       textView.setText(roundedvalue);  
                     }
                 });
    
    
    
                    }
                }, 0, 1*1000);