Search code examples
androidkotlintimecalendardate-format

Trying to perform a text change in my textview at a reoccurring time on daily basis in my android project


let say i will like to automatically change my textview text at 02:00pm everyday how do I implement this functionality.

val df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
        val systemDat = Calendar.getInstance(Locale.JAPAN).after(df)
        if (systemDat) {
            binding.includeTokyoSession.text_one.text = "successful"
        } else {
            binding.includeTokyoSession.text_one.text = "failure"
        }

Solution

  • I suppose you want to change the text of your TextView after a particular time, but it seems that you're not aware of the date when comparing and you have a couple of mistakes in your code.

    First, this line of code:

    DateFormat.getTimeInstance(DateFormat.SHORT, Locale.JAPAN).parse("2:00pm")
    

    will return a Date instance with this date and time in your local timezone 01-01-1970 02:00:00. However, you need to get a Date instance with today's date and the time 14:00:00.

    Second, this line of code:

    Calendar.getInstance(Locale.JAPAN).after(df)
    

    this is a wrong usage of the Calendar::after() function, and that's because you can only pass a Calendar object to the function in order to get the right comparison result, otherwise it will always return false.

    In your case you're passing a Date object.

    Following is the implementation of the Calendar::after() function.

    public boolean after(Object when) {
        return when instanceof Calendar
            && compareTo((Calendar)when) > 0;
    }
    

    If you want to proper compare the current time today with 14:00 (comparing only the time today), here is a modification to your code:

    val calendarToCompare = Calendar.getInstance(Locale.JAPAN).apply {
        set(Calendar.HOUR_OF_DAY, 14)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }
    
    val systemDat = Calendar.getInstance().after(calendarToCompare)
    
    if (systemDat) {
        textview.text = "successful"
    } else {
        textview.text = "failure"
    }
    

    If you want to perform a lifecycle-aware view update (ex. to set the text of your textview), you can check this gist.