简体   繁体   中英

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? Any ideas.

This eventHandler is called in onCreate (Main Activity):-

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):-

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 . Everytime you create an Activity onCreate() and onResume() are called. You are getting a NUllpointerException because, in onResume() (which is called before onDayLongPress ) selectDate is not initalized and therefore null . You could initalize selectDate in one of the 2 methods to avoid the exception.

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.

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