0

I have a layout that will display a TextView which is used to display a ticking time.I followed the codes from this link

How to Display current time that changes dynamically for every second in android

but I get an error of

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I had the same problem here but I fixed it

Intent extras null on configuration change

Here are the Java codes

void clockTicking(){
final CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {

  public void onTick(long millisUntilFinished) {
    timeDisplay = (TextView)findViewById(R.id.txtTime);

    Calendar c = Calendar.getInstance();
    timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND)+" PM");
  }
  public void onFinish() {
  }
};
newtimer.start();
Community
  • 1
  • 1
Fay Zan
  • 165
  • 2
  • 17

2 Answers2

2

In your code timeDisplay object is null.

Make sure your textview id is correct. Double check this line timeDisplay = (TextView)findViewById(R.id.txtTime);

I think your id txtTime is incorrect.

Hope it will helpful.

Mitesh Vanaliya
  • 2,491
  • 24
  • 39
  • Thanks for the reply,I'm pretty sure my `TextView` id is correct because that's the only variable I use to display anything.If it did not exist then Android Studio would surely detect it.But to be safe I still checked if it was correct or not. – Fay Zan Aug 05 '16 at 01:24
0

Okay so I finally fixed it,the only reason why it crashed was because during orientation the layout I used has no TextView which Mitesh Vanaliya stated was correct.So I fixed it by turning it off upon orientation using this code thanks to Ayyappan from

How to Display current time that changes dynamically for every second in android

Turning off the clock

void clockUnTicking(){
CountDownTimer newtimer = new CountDownTimer(1000000000, 1000) {

  public void onTick(long millisUntilFinished) {
    timeDisplay = (TextView)findViewById(R.id.txtTime);

    Calendar c = Calendar.getInstance();
    timeDisplay.setText(c.get(Calendar.HOUR)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND));
  }
  public void onFinish() {

  }
};
newtimer.cancel();
}

to turn it on just replace newtimer.cancel(); with newtimer.start()

Community
  • 1
  • 1
Fay Zan
  • 165
  • 2
  • 17