I am new to kotlin and android studio and i am trying to have the day displayed in a text view. My problme is that only the number 1 to 7 is displayed acording to the current day but not the name of the day what do i have to change to fix this?
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fun dayOfWeek() {
val day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
println(
when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Time has stopped"
}
)
}
tag = findViewById(R.id.Tag)
tag.text = day.toString()
2
Answers
In your code,
day
is an Int property.You have created a function called
dayOfWeek()
that you never call so that code never runs.When you do
tag.text = day.toString()
, it is looking at theday
property, not theday
variable inside your function. It is usually a bad idea to name a variable the same thing as some property in the same class because it makes the code confusing to read. But that doesn’t matter either way in this case because both of them are Ints.In your
dayOfWeek()
function, you are using awhen
expression to covertday
to a String, but you are just printing it. You are not storing it in a variable such that it can be used for anything else, like setting it on a TextView.You can make your function return a String, and use it that way. I would also move your function outside the
onCreate()
function. It is unusual to create a function inside another function for this kind of task.Or to do this the easy way, and with proper language support:
java.time
The
java.util
Date-Time API and their formatting API,SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.Solution using
java.time
, the modern Date-Time API: There are a couple of ways to do it as shown below:ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for
java.time
.