When I try to get the current time I am using below code. But it shows Null Pointer Exception
in Apple device. It is working fine in Android device.
How to solve this exception? What's wrong in my code?
String hourValue = "";
String minutesValue = "";
String amPm = "AM";
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int amPmVal = now.get(Calendar.AM_PM);
if(hour > 12){
hour = hour -12;
}
if(hour == 0){
hour = 12;
}
if(amPmVal == 1){
amPm = "PM";
}
hourValue = hour+"";
minutesValue = minute+"";
if(minute < 10){
minutesValue = "0"+minutesValue;
}
return hourValue+":"+minutesValue+" "+amPm;
Calendar.getInstance()
returnsNullPointerException
in ios device?
No it doesn't. And it doesn't return null
either.
Here is you code.
Calendar now = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
You obtained an instance of Calendar
and assigned it to now
.
Then you used the Calendar
object that a different variable called calendar
refers to.
Unless you have initialized the calendar
variable somewhere else, the second statement will give you a NPE.
Solution: use the value of now
!
When I try to get the current time I am using below code. But it shows Null Pointer Exception in Apple device. It is working fine in Android device.
Presumably on the Android device you are initializing the calendar
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.