Android Javamail Attachment抛出java.lang.NullPointerException

时间:2016-10-31 09:12:04

标签: java android javamail attachment

大家好我正在尝试制作电子邮件发件人应用,发送电子邮件的工作正常但是当我尝试添加附件时,它会显示NullPointerException

这是错误

W/System.err: java.lang.NullPointerException
    W/System.err:     at com.example.milingona.anew.MainActivity.addAttachment(MainActivity.java:120)
    W/System.err:     at com.example.milingona.anew.MainActivity.onActivityResult(MainActivity.java:96)
    W/System.err:     at android.app.Activity.dispatchActivityResult(Activity.java:5322)
    W/System.err:     at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
    W/System.err:     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
    W/System.err:     at android.app.ActivityThread.access$1100(ActivityThread.java:141)
    W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
    W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
    W/System.err:     at android.os.Looper.loop(Looper.java:137)
    W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5103)
    W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
    W/System.err:     at java.lang.reflect.Method.invoke(Method.java:525)
    W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
    W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
    W/System.err:     at dalvik.system.NativeStart.main(Native Method)

这里是代码

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

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

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

public class MainActivity extends AppCompatActivity {

    Button btn;
    ImageView imageView;
    String root;
    String imageFolderPath;
    String imageName;
    Uri fileUri;

    private static final String username = "use@gmail.com";
    private static final String password = "*********";
    private Multipart _multipart;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.captureImage);
        imageView= (ImageView) findViewById(R.id.imageView);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_NETWORK_STATE, Manifest.permission.INTERNET, Manifest.permission_group.STORAGE }, 0);
        }
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                root = Environment.getExternalStorageDirectory()
                        + "/ANew";

                // Creating folders for Image
                imageFolderPath = root + "/Images";
                File imagesFolder = new File(imageFolderPath);
                imagesFolder.mkdirs();
                Date d = new Date();
                CharSequence s = DateFormat.format("hh-mm-ss", d.getTime());
                // Generating file name
                imageName = "img-" + s + ".jpg";

                // Creating image here

                File image = new File(imageFolderPath, imageName);

                fileUri = Uri.fromFile(image);

                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

                startActivityForResult(takePictureIntent, 1);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            addAttachment(fileUri.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
sendMail("receiver@gmail.com","Subject","MESSAGE");
    }
    private void sendMail(String email, String subject, String messageBody) {
        Session session = createSessionObject();

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

        }
    }

    public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);

        _multipart.addBodyPart(messageBodyPart);
    }

    private Message createMessage(String email, String subject, String messageBody, Session session) throws MessagingException, UnsupportedEncodingException {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("user@gmail.com", "Alban Gashi"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
        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(username, password);
            }
        });
    }

    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;
        }
    }
}

顺便说一下,我在manifest

中添加了权限
<uses-feature android:name="android.hardware.camera2"></uses-feature>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>

1 个答案:

答案 0 :(得分:2)

您没有在任何地方初始化_multipart变量,因此在尝试访问MainActivity第120行的方法.addBodyPart时会出现NullPointerException。