2

I have set display current date on textview in my android app, it work, but it doesn't change to new date auto after 00:00:00 AM until we close App and open back.Please help. Here is my code:

TextView tv = (TextView) findViewById(R.id.date);
    String ct = DateFormat.getDateInstance().format(new Date());
    tv.setText(ct);
Samith FP
  • 31
  • 7
  • This is happening because that initialization happens only ones – N J Jun 04 '16 at 03:20
  • so please advice what i can do to let it initialization always – Samith FP Jun 04 '16 at 03:23
  • you want to change `TextView` content only at 12:00 ? – N J Jun 04 '16 at 03:25
  • You would need to decide when you want the date to change (e.g. onResume would happen when returning from an activity started from this activity, or you could have a button an change on the onClick (when button is clicked)). – MikeT Jun 04 '16 at 03:25
  • 1
    you can also user `AlarmManager` http://stackoverflow.com/questions/10700003/android-start-task-within-specific-time – N J Jun 04 '16 at 03:26
  • no i don't want to use button, i want it automatically change by itself at 12:00 AM – Samith FP Jun 04 '16 at 03:30

1 Answers1

4

It's gonna be a pretty good amount of code to add, but, here's what you have to do.

Assuming that you have a class extending Activity, you'll need to override onPause() and onResume().
For example:

@Override
protected void onPause() {
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
}

In these two methods, you are going to have to register and unregister an IntentFilter.
Create the IntentFilter as a global variable. We'll also create the listener that'll be used later.

private IntentFilter filter;
private final BroadcastReceiver listener;

Instantiate it in your onCreate().

filter = new IntentFilter();
filter.addAction(Intent.ACTION_DATE_CHANGED);

Also, directly after that, we'll create the listener to tell it what to do when the date changes.

listener = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent i) {
        TextView tv = (TextView) findViewById(R.id.date);
        String ct = DateFormat.getDateInstance().format(new Date());
        tv.setText(ct);
    }
};

Finally, we have to register and unregister the listener when the app opens and closes.

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(listener, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(listener);
}

And, there you have it! Should automatically update when the date changes now. Also, I wouldn't recommend re-initializing the TextView every time the date changes, but your current code was that, so I left it.

More info from Ben English

Community
  • 1
  • 1
Arm
  • 88
  • 3