Kala J
Kala J

Reputation: 2070

Why isn't my current datetime in sync with the system clock all the time?

Although getting the instance of the current datetime works for when I launch my activity, if I go to another screen and click on the back button to go back to my previous activity, the datetime stays the same as when I first accessed the activity. Also if I keep my activity idle, the time does not update either. Is it because I am getting only an instance of the datetime? How can I prevent this?

Inside Activity:

long currentDateTime = System.currentTimeMillis();
Date date = new Date(currentDateTime);

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String formatDate = format.format(date);

TextView currentDateTextView = ((TextView) findViewById(R.id.current_datetime));
currentDateTextView.setText(formatDate);

SimpleDateFormat formatLong = new SimpleDateFormat("EEE, MMMM d");
String formatDateLong = formatLong.format(date);

TextView currentDateLongTextView = ((TextView) findViewById(R.id.current_datetime_long));
currentDateLongTextView.setText(formatDateLong);

EDIT:

Even though I put the above is in my onResume() method, I still have on problem:

If I remain on the screen, the time is static and does not update with my system time. What do I do in that event?

Upvotes: 0

Views: 144

Answers (1)

Kala J
Kala J

Reputation: 2070

I used TextClock instead

    <TextClock
    android:id="@+id/current_datetime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:format24Hour="HH:mm"
    android:format12Hour="HH:mm" />

and it works just fine! I didn't know about TextClock widget previously.

Upvotes: 1

Related Questions