Reputation: 11
package com.example.prototypeb.ui.game.Game_components;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.prototypeb.R;
import com.example.prototypeb.ui.game.GameFragment;
public class Game_adverbs extends AppCompatActivity {
TextView timer;
CountDownTimer countdown;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_adverbs);
setTitle("Adverbs");
countdown.start();
Button backbutton = findViewById(R.id.backbtn1);
backbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), GameFragment.class);
startActivity(intent);
}
});
timer = findViewById(R.id.text_view_timer);
countdown = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText((int) (millisUntilFinished/1000));
}
public void onFinish() {
timer.setText("TIME'S UP!");
}
};
}
}
here is part of my code for an activity. I actually want my timer to start right away when my activity is started. My app crashes instantly as soon as my activity is started and I have tested and identified that the problem is within/ around the CountDownTimer code
Upvotes: 0
Views: 47
Reputation: 50
You are calling countdown.start();
before defining the countdown
object
Upvotes: 1
Reputation: 12204
The exception is arising because you're calling countdown.start()
before initializing the countdown
object.
So moving countdown.start();
after initializing countdown
, or at the bottom of onCreate
method may work.
Something like this...
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_adverbs);
setTitle("Adverbs");
Button backbutton = findViewById(R.id.backbtn1);
backbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), GameFragment.class);
startActivity(intent);
}
});
timer = findViewById(R.id.text_view_timer);
countdown = new CountDownTimer(10000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText((int) (millisUntilFinished/1000));
}
public void onFinish() {
timer.setText("TIME'S UP!");
}
};
countdown.start();
}
Upvotes: 1