【问题标题】:null Pointer Exception when parsing date with Simple Date format使用简单日期格式解析日期时出现空指针异常
【发布时间】:2018-05-20 16:17:49
【问题描述】:

我在将我的字符串转换为日期时遇到问题,它给了我一个空指针异常,我已经尝试了所有方法。

这就是我从 calendarView 将字符串输入数据库的方式

mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(@NonNull CalendarView calendarView, int i, int i1, int i2) {
            string = (i1 + 1) + "/" +i2 + "/" + i;
}
        });

String key = mDatabase.push().getKey();

                HashMap<String, String> dataMap = new HashMap<>();
                dataMap.put("Date", date);
                dataMap.put("Key", key);
 mDatabase.child(key).setValue(dataMap);

然后当我从我的数据库中检索它时,我会像这样格式化它

databaseReference = FirebaseDatabase.getInstance().getReference().child("Groups").child("JMHyOvgCDvdKEZuReJvdGcExEnX2").child("HomeFragment").child("FreezerItems");
        valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                HashMap<String, String> value = (HashMap<String,String>) dataSnapshot.getValue();
                if (value != null){
                    String name = value.get("Name");
                    String date = value.get("Date");

                    try {
                        dateFormat = new Date();
                        dateFormat = new SimpleDateFormat("M/dd/yyyy", Locale.US).parse(date);

                    } catch (ParseException e) {
                        Log.wtf("FailedtoChangeDate", "Fail");
                    }

我的问题是当我尝试将字符串转换为 M/dd/yyyy 格式时,即使字符串中的日期格式类似于“5/30/2018”

调试时的屏幕截图

【问题讨论】:

  • 这里也贴出这个变量的值 String date = value.get("Date");
  • 更新了我的答案检查,它将起作用:)
  • 顺便考虑一下扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友,并将ThreeTenABP添加到您的Android项目中,以便使用java.time,现代Java日期和时间API .使用起来感觉好多了。
  • 请发布您的堆栈跟踪(以某种方式掌握它,这很重要)。

标签: android date firebase nullpointerexception datetime-parsing


【解决方案1】:

更新我的答案:-

您的日期输入05/20/2018

String input_date = "05/20/2018";  
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");  
try {  
    Date date = format.parse(input_date );  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

【讨论】:

  • 在 2018 年 5 月 20 日更新了这个答案,试试吧,它会起作用的 :)
  • 再次检查这个值 String date = value.get("Date");并调试您的代码
  • 我什至尝试复制数据的输入方式并将其粘贴到检索数据的位置,因此没有错误但仍然无法工作
  • 它还在崩溃吗?
  • 是的,我也不确定如何调试我的代码,我会更新我的问题
【解决方案2】:

您的屏幕截图非常有用。它显示value 为名称和日期返回null。因此,您尝试从该地图中取出的值不存在。这就是为什么datenull 而你得到你的NullPointerException

为什么地图中没有日期(也没有名字)在我们可以在问题中看到的代码之外,所以我不知道。

【讨论】:

    猜你喜欢
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2018-04-18
    • 1970-01-01
    相关资源
    最近更新 更多