java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread

十年热恋 提交于 2020-06-18 03:29:23

问题


I know this may be a duplicate but my situation is different which requires some explanation on this specific issue.

I'm getting the error :

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

In the onClick the method addEvent is called from the class MyCalendar

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyCalendar myCalendar = new MyCalendar();
            myCalendar.addEvent();
          //  myCalendar.AddEvent(2,context);
       }
    });

It calls the below method

public void addEvent(){
    Calendar beginTime = Calendar.getInstance();
    beginTime.set(2018, 11, 14, 7, 30);
    Calendar endTime = Calendar.getInstance();
    endTime.set(2018, 11, 14, 8, 30);
        Intent intent = new Intent(Intent.ACTION_INSERT)
            .setData(Events.CONTENT_URI)
            .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
            .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
            .putExtra(Events.TITLE, "TEST ANDROID")
            .putExtra(Events.DESCRIPTION, "EVENT HAS BEEN ADDED FROM ANDROID STUDIO")
            .putExtra(Events.EVENT_LOCATION, "GIBRALTAR")
            .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
            .putExtra(Events.CALENDAR_ID, 2)
            .putExtra(Intent.EXTRA_EMAIL, "example@test.com");
    startActivity(intent);
}

This method does work when it is declared within the MainActivity but now that I have moved it to another class, it is showing that above exception.

How can I fix this?


回答1:


You will need to pass the calling activity as a context parameter to your new MyCalendar(context) call. Then from your calendar class, invoke context.startActivity(intent)




回答2:


Here what to do Add a new method to calendar class

class Calendar {
...
private Context controller
 public void setController(Context cnts){ this.controller = cnts}
public void addEvent(){
// change it to
controller.startActivity(intent);
}
}

in Onclick method

button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyCalendar myCalendar = new MyCalendar();
            myCalender.setController(this.MainActivity)
            myCalendar.addEvent();
          //  myCalendar.AddEvent(2,context);
       }

I use kotlin. and am rusty in Java(Sorry for the syntax if its wrong) });



来源:https://stackoverflow.com/questions/53748248/java-lang-nullpointerexception-attempt-to-invoke-virtual-method-android-app-ac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!