安卓获取java。lang.NumberFormatException:对于输入字符串,尝试在消息中显示数据时为“null”
我不断遇到这个问题,我试图显示消息在消息传递应用程序中发布的日期,我不断收到这个错误,应用程序不断崩溃
String message = chatList.get(position).getMessage();
String timeStamp = chatList.get(position).getTimestamp();
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(Long.parseLong(timeStamp));
String dateTime = DateFormat.format("dd/MM/yyyy hh:mm aa", cal).toString();
holder.messageTv.setText(message);
holder.timeTv.setText(dateTime);
这是我收到的logcat错误:
2020-09-02 22:10:08.411 13445-13445/com.x00122898.meetupproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.x00122898.meetupproject, PID: 13445
java.lang.NumberFormatException: For input string: "null"
at java.lang.Long.parseLong(Long.java:594)
at java.lang.Long.parseLong(Long.java:636)
at com.x00122898.meetupproject.ChatActivity$1.onDataChange(ChatActivity.java:107)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
at 安卓.os.Handler.handleCallback(Handler.java:888)
at 安卓.os.Handler.dispatchMessage(Handler.java:100)
at 安卓.os.Looper.loop(Looper.java:213)
at 安卓.app.ActivityThread.main(ActivityThread.java:8178)
at java.lang.reflect.Method.invoke(Native Method)
at com.安卓.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
at com.安卓.internal.os.ZygoteInit.main(ZygoteInit.java:1101)
2020-09-02 22:10:08.422 13445-13445/com.x00122898.meetupproject I/Process: Sending signal. PID: 13445 SIG: 9
任何帮助都将不胜感激~
# 1 楼答案
问题似乎发生在聊天室活动中。java第107行,其中的值字面上是“null”。参见前面的答案 numberformatexception-for-input-string-null
# 2 楼答案
问题在于这两行代码:
变量timeStamp包含字符串/单词“null”,当您尝试将其解析为Long时,它抛出NumberFormatException。 必须捕获异常或验证时间戳是否包含数值(请参见How to check if a String is numeric in Java)
另外,可能方法getTimestamp()没有返回正确的变量,或者时间戳从未保存或发送