0

我需要发送电子邮件,所以我创建了一个类,但 startActivity(intent) 中出现错误。此代码在 Main Activity 中运行良好。这里的代码:

public class SendEmail extends Activity {
private String emailTo;
private String subject;
private String message;

public SendEmail(String AEmailTo, String ASubject, String AMessage) {
    this.emailTo = AEmailTo;
    this.subject = ASubject;
    this.message = AMessage;
}

public void Send(){
     try {          
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("application/octet-stream");
        intent.putExtra(Intent.EXTRA_SUBJECT, this.subject);
        intent.putExtra(Intent.EXTRA_TEXT, this.message);
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] {this.emailTo});
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
       } catch (Exception e) {   
         Log.e("SendMail", e.getMessage(), e);   
       }
    }

}

日志猫:

11-12 10:54:56.783: E/SendMail(19773): null
11-12 10:54:56.783: E/SendMail(19773): java.lang.NullPointerException
11-12 10:54:56.783: E/SendMail(19773):  at    android.app.Activity.startActivityForResult(Activity.java:2817)
11-12 10:54:56.783: E/SendMail(19773):  at    android.app.Activity.startActivity(Activity.java:2923)
11-12 10:54:56.783: E/SendMail(19773):  at   idealbrasil.forcav.android.SendEmail.Send(SendEmail.java:52)
11-12 10:54:56.783: E/SendMail(19773):  at idealbrasil.forcav.android.util.funcoes.SendEmail(funcoes.java:221)
11-12 10:54:56.783: E/SendMail(19773):  at idealbrasil.forcav.android.util.TrataErro$1.onClick(TrataErro.java:136)
11-12 10:54:56.783: E/SendMail(19773):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:158)
11-12 10:54:56.783: E/SendMail(19773):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-12 10:54:56.783: E/SendMail(19773):  at android.os.Looper.loop(Looper.java:123)
11-12 10:54:56.783: E/SendMail(19773):  at android.app.ActivityThread.main(ActivityThread.java:4627)
4

1 回答 1

0

startActivity() 的上下文为空,这就是您收到空指针异常的原因。看起来您是 Android 新手,并且该过程不符合编码约定。

您可以在类中使用 onCreate() 方法,然后使用类 startActivity(),或者将上下文传递给该函数,然后调用

context.startActivity(intent);

于 2012-11-12T13:49:03.177 回答