Reputation: 7110
I am setting a default time in my code and wish to set the time picker dialog to that time when the user clicks on it. Below is the code:
startTimeButton?.setOnClickListener {
val calendar = Calendar.getInstance()
val timeSetListener = TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute ->
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
calendar.set(Calendar.MINUTE, minute)
startTimeButton?.text = SimpleDateFormat("HH:mm").format(calendar.time)
SharedPreferences.setStartTime(activity, startTimeButton?.text.toString())
}
val startTimeArray: List<String> = SharedPreferences.getStartTime(context).split(":")
TimePickerDialog(activity, timeSetListener, calendar.get(startTimeArray[0].toInt()), calendar.get(startTimeArray[1].toInt()), true).show()
}
If my start time is 09:00, the time picker dialog points to 01:01 and if it's 17:00, then time picker dialog crashes with "java.lang.ArrayIndexOutOfBoundsException: length=17; index=17" error.
What am I doing wrong here?
Upvotes: 0
Views: 1094
Reputation: 1007296
The get()
function on Calendar
returns a value for a given field identifier. Examples include calendar.get(Calendar.HOUR_OF_DAY)
and calendar.get(Calendar.MINUTE)
.
You appear to be passing into get()
hours and minutes as integers. Those are not field identifiers.
I suspect that this is closer to what you want:
TimePickerDialog(activity, timeSetListener, startTimeArray[0].toInt(), startTimeArray[1].toInt(), true).show()
Also, please make sure you are handling configuration changes. For example, use a DialogFragment
to show your TimePickerDialog
.
Upvotes: 4