简体   繁体   English

从onResume调用方法时发生NullPointer异常

[英]NullPointer Exception when calling a method from onResume

I am setting my selectDate on longPress but why does it say that my selectDate is null in HighlightCalander function? 我在longPress上设置了selectDate,但为什么在HighlightCalander函数中却说我的selectDate为null? Any ideas. 有任何想法吗。

This eventHandler is called in onCreate (Main Activity):- 在onCreate(主要活动)中调用此eventHandler:

calendarview.setEventHandler(new CalendarView.EventHandler()
        {
            @Override
            public void onDayLongPress(Date date)
            {
                DateFormat df = SimpleDateFormat.getDateInstance();
                selectDate = date;
                System.out.println(selectDate);
                intent1 = new Intent(getApplicationContext(), MakeAppointmentsActivity.class);
                intent1.putExtra("DATE",df.format(date));
                startActivity(intent1);
            }

This function is called in onResume (Main Activity):- 此函数在onResume(主要活动)中调用:-

public void HighlightCalendar()
    {
        intent2 = getIntent();
        // get my boolean from save button
        boolean savedDate = intent2.getBooleanExtra("savedDate", false);
        // if i pressed my saved button
        if(savedDate) {
            Toast.makeText(this,"true",Toast.LENGTH_SHORT).show();
            try {
                DateFormat df = SimpleDateFormat.getDateInstance();
                SimpleDateFormat curFormater = new SimpleDateFormat("MMM yyyy");
                String dateString = df.format(selectDate);
                Date dateObj = curFormater.parse(dateString);
                events.add(dateObj);
                calendarview.updateCalendar(events);
            }catch (ParseException e){
                e.printStackTrace();
            }
}
        else
        {
            Toast.makeText(this,"false",Toast.LENGTH_SHORT).show();
        }
    }

You are assigning a value to selectDate in onDayLongPress but you are using it in onResume . 您在onDayLongPressselectDate分配了一个值,但在onResume中使用了它。 Everytime you create an Activity onCreate() and onResume() are called. 每次创建Activity ,都会调用onCreate()onResume() You are getting a NUllpointerException because, in onResume() (which is called before onDayLongPress ) selectDate is not initalized and therefore null . 您将收到NUllpointerException因为在onResume() (在onDayLongPress之前onDayLongPress )中, selectDateselectDate ,因此为null You could initalize selectDate in one of the 2 methods to avoid the exception. 您可以使用两种方法之一来selectDate以避免异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM