0

I'm just learning Android and I'm already having trouble with complete basics:

I'd like to have a timer that increments a TextView but it crashes the first time the timer ticks.

Here's my code:

public class Game extends Activity {

Timer timer = new Timer();
int i = 0;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    text = (TextView) findViewById(R.id.timerText); 
    text.setText("0");

    timer.schedule(new TimerTask() {
        public void run() {
            i++;
            System.out.println(i);
            text.setText(i + "");
            if(i>100) timer.cancel();
        }
    }, 1000, 1000);
}
}

Here's my XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

...

<TextView
    android:id="@+id/timerText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

I found a ton of solutions for setText crashing but none of them seemed to fix this.

franga2000
  • 587
  • 1
  • 9
  • 19

3 Answers3

0

Look at this : Android: Accessing UI Element from timer thread

Explantation : you've got error because you try accessing to UI element(in your case - textView) from separate background thread.

Also look this answer with simplifiest example: https://stackoverflow.com/a/6702767/2956344

Community
  • 1
  • 1
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
0

if you are accesing to UI element in the timer run you should use a Handler or runOnUITheard.

Please check:

http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

and

Android: Accessing UI Element from timer thread

Community
  • 1
  • 1
fpanizza
  • 1,589
  • 1
  • 8
  • 15
0

You need to call text.setText(i + ""); from runOnUiThread()

CodeWarrior
  • 5,026
  • 6
  • 30
  • 46