Android TimePicker Dialog method question

Asked 2 years ago, Updated 2 years ago, 25 views

I have a question because there is something that does not work well in setting the time using TimePickerDialog.

 private TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            if(hourOfDay < 10){
                strHourOfDay = "0" + hourOfDay;
            } } else { strHourOfDay = String.valueOf(hourOfDay);}

            if(minute < 10){
                strMinute = "0" + minute;
            } } else { strMinute = String.valueOf(minute);}

            period.put("hour",strHourOfDay);
            period.put("minute",strMinute);

            periodTime.setText(strHourOfDay + ":" + strMinute);
        }
    };

In the above code, hourOfDay is stored well through the if statement without error. However, if the minute is less than 10, it is saved, but if it exceeds 10, strMinute = String.valueOf(minute); where the strMinute is null. Why is there a difference when both hourOfDay and minute are int values?

Looking at the debug window,

The icon in front of hourOfDay and minute is different, is it because of this? I have no idea.

android

2022-09-22 20:57

1 Answers

Does the strMinute=String.valueOf(minute); line become null when the strMinute=30 line is executed in the debugging window of the screen shot? It is possible to step over by line using a debugger, so I think we need to check it again. There is no problem with the code you uploaded. Check if there are any parts where strMinute is null due to other codes.

The icon only indicates the type of variable. Please refer to the item Variable types in the link below. The icon for minute means the primary type. P of hourOfDay is not mentioned, so I don't know the exact meaning.

And if you want to match the digits, use the String.format() function. You can modify the code as below. If, else statements can be removed, resulting in simplified code.

strHourOfDay = String.format("%02d", hourOfDay);
strMinute  = String.format("%02d", minute);


2022-09-22 20:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.