空上下文问题

时间:2016-12-31 07:25:29

标签: java android nullpointerexception

我有getdata个班级,还有一个班级Checksgetdata正在将context传递给Checks以调用其互联网连接检查方法。但是在这里我得到了一个nullpoint异常的错误。要检查mcontext是否为null我是获取设备ID并获取值。

getdata类的代码:

public class getdata extends AsyncTask<Void, Void, Void> {
    private Context mcontext;
    private String message;


    getdata(Context context, String msg) {
        this.mcontext = context;
        this.message = msg;
    }

    Checks checks = new Checks(mcontext);

    @Override
    protected Void doInBackground(Void... params) throws IllegalStateException {
        System.out.println("Starting");

TelephonyManager telephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String id = telephonyManager.getDeviceId();
        System.out.println(id);
        try {
            if (checks.checkinternet()) {
Log.i("Internet Status","Found");
}
}

Checks类的代码:

public class Checks {

    private Context mContext;

    public Checks(Context context) {
        this.mContext = context;
    }



    boolean checkinternet() {


        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeinternet = connectivityManager.getActiveNetworkInfo();
        return activeinternet != null && activeinternet.isConnected();

    }}

现在通过NPE检查互联网状态?不知道我错误的地方。

1 个答案:

答案 0 :(得分:2)

在构造函数中分配void sendMail(char * msg, char * recipientMail){ char cmd[100]; char subject[30]; char body[60]; sprintf(body, "Intruder detected!!!\n%s", msg); strcpy(subject, "\"ALARM - SECURITY BREACH\""); sprintf(cmd,"echo \"%s\" | mutt -s %s %s &", body, subject, recipientMail); printf("%s\n\n", cmd); system(cmd); } 之前,您正在调用您的支票。

所以修改你的代码如下所示并在构造函数中初始化Check: -

while(1){

        sleep(1);

        if(prev_state == triggered && !emailDetach){
            if(!logAlarm()){
                printf("Error writing to log file!!!\n");
            }
            emailDetach = true;
        }
        //printf("Czas od poprzedniego alarmu: %d", millis() - alarmTriggeredTime);
        if((prev_state == triggered) && (millis() - alarmTriggeredTime >= ALARM_TIME)){

            digitalWrite(ALARM_ON_DIODE, LOW);
            digitalWrite(ALARM_OFF_DIODE, HIGH);
            //warunek czasowy osobno na syrene TODO
            if(!silentMode && (millis() - alarmTriggeredTime >= siren_alarm_time)){
                digitalWrite(SIREN, LOW);
            }
            prev_state = nottriggered;
        }

}