代码:
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
String message = chatList.get(position).getMessage();
String timeStamp = chatList.get(position).getTimestamp();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(timeStamp));
String dataTime = format("MMMM d, h:mm a", cal).toString();
holder.timeTv.setText(dateTime);
错误信息:
java.lang.NullPointerException: Attempt to invoke virtual method 'long
java.lang.Long.longValue()' on a null object reference
调试您的代码/打印日志,并确保您没有获得 getTimestamp 的空值,然后尝试这个它会起作用
String dataTime = String.valueOf(format("MMMM d, h:mm a", cal));
我也面临着同样的问题。我使用了以下代码,它对我有用。
private static DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.toFormatter();
private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm a");
然后在 onBindViewHolder 中,我添加了以下代码片段:
Instant inst;
if (timeStamp == null) {
inst = Instant.now();
} else {
inst = Instant.from(timestampFormatter.parse(timeStamp));
}
String dateTime = inst.atZone(ZoneId.systemDefault()).format(dtf);