发送电子邮件时发生java.lang.NullPointerException错误-Android

发送电子邮件时发生java.lang.NullPointerException错误-Android,android,Android,我在执行代码时遇到java.lang.NullPointerException错误,我无法找出它缺少什么。有人能指出错误吗?对我来说,这些代码看起来不错,但发送邮件功能仍返回NUll: 代码: import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import an

我在执行代码时遇到java.lang.NullPointerException错误,我无法找出它缺少什么。有人能指出错误吗?对我来说,这些代码看起来不错,但发送邮件功能仍返回NUll:

代码:

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GmailSender {

     private static final String username = "abc@gmail.com";
        private static final String password = "abc123";

    public void sendMail(String email, String subject, String messageBody) {
        Session session = createSessionObject();

        try {
            Message message = createMessage(email, subject, messageBody, session);
            new SendMailTask().execute(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("abc@gmail.com", "Project"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("abc@gmail.com"));
        message.setSubject(subject);
        message.setText(messageBody);
        return message;
    }

    private Session createSessionObject() {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");

        return Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("abc@gmail.com", "abc");
            }
        });
    }

    private class SendMailTask extends AsyncTask<Message, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //progressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Sending mail", true, false);
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progressDialog.dismiss();
        }

        @Override
        protected Void doInBackground(Message... messages) {
            try {
                Transport.send(messages[0]);
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


}
文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.api.posttestcases"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />


           <uses-permission android:name="android.permission.INTERNET" />
           <uses-permission android:name="android.permission.GET_ACCOUNTS" />
           <uses-permission android:name="android.permission.USE_CREDENTIALS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.api.posttestcases.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
编辑:

首先。实例化sender变量

public void sendGmail(View view) {
    try {   
        sender = new GmailSender();
        sender.sendMail("abc@gmail.com", "Test Mail", "Post TestMail");
        //sender.start();
    } catch (Exception e) {   
        Log.e("SendMail", e.getMessage(), e);   
    } 
}
将构造函数添加到GmailSender类

public GmailSender() { }
主要答覆:

我猜想您的错误可能在异步任务中。我用注释编辑了代码

@Override
protected void onPostExecute(Void aVoid) {
    // aVoid is null. Do you really need to call super.onPostExecute() ? I wo
    super.onPostExecute(aVoid);

    // progressDialog is null? you commented out the instantiotion
    progressDialog.dismiss();
}

@Override
protected Void doInBackground(Message... messages) {
    try {
        Transport.send(messages[0]);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    // I would return something else. like a boolean true if no error else false !
    return null;
}

sendGmail在哪里??我看不见。NPE正在活动中。您是否正在声明Gmail发件人对象,但没有初始化它?是否也可以从MainActivity发布sendGmail方法?邮件发送方法看起来正常。是的。发件人为空。@user3688062您正在对空字段调用方法。这就是引发NullPointerException的原因。如果运行调试器,这可能会被发现并解决。另请参阅关于如何格式化简短、自包含、正确、可编译且对问题有用的示例的建议-您的代码没有格式化、注释和解释,如果没有容易发现的错误,很难提供帮助。这并没有解决MainActivity.java第80行中OP的问题。我喜欢您的答案,但是不要声明publicgmailsender{},因为构造函数没有重载。
public GmailSender() { }
@Override
protected void onPostExecute(Void aVoid) {
    // aVoid is null. Do you really need to call super.onPostExecute() ? I wo
    super.onPostExecute(aVoid);

    // progressDialog is null? you commented out the instantiotion
    progressDialog.dismiss();
}

@Override
protected Void doInBackground(Message... messages) {
    try {
        Transport.send(messages[0]);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
    // I would return something else. like a boolean true if no error else false !
    return null;
}