Madona wambua
Madona wambua

Reputation: 1428

Implementing Timer in Android See code below for assistance

Hello everyone I have my MathQuestions Class and i want the timer to start once the play button in MainActivity is pressed (onClickStart). I am having difficulties in knowing were to start the timer. Any help offered will be appreciated. I have written down what i want done in the GameTimer class with my ImageButton and TextView but I have tried several ways with no luck. The app keeps closing.

my Code where the MathQuestion class is started.

This is my play button;

 public void onClickStart(View view){

            EditText nameInput = (EditText)findViewById(R.id.playerName);
            name = nameInput.getText().toString();
        Intent i = new Intent(this,MathQuestions.class);
                    i.putExtra("levelSelected", Integer.valueOf(radiobutton));
                    startActivity(i);

My math_layout xml which is used in both MathQuestion and GameTimer This is the pause imagebutton and the OnTick TextView

<ImageButton
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_pause_white_18dp"
        android:background="@drawable/circle"
        android:id="@+id/pause"
        android:elevation="4dp"
        android:onClick="pause"
        android:layout_below="@+id/questionField"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/ontick"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FF0000"
        android:elevation="5dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

The Error;

onTick(GameTimer.java:48)
            at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:133)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)

Upvotes: 0

Views: 49

Answers (1)

EEJ
EEJ

Reputation: 678

The issue is that you are trying to modify the view from background thread which is the overrided method of CountdownTimer.

Try to update your view like this from background thread. eg:-

text.post(new Runnable(){
     @Override
     Public void run(){
         text.setText("set your text");
    }
});

Upvotes: 1

Related Questions