我在执行代码时遇到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;
}
}
}
主要活动:
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
GmailSender sender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public void sendGmail(View view)
{
try {
//sender = new SendGmail("abc@gmail.com", "abc123");
sender.sendMail("abc@gmail.com", "Test Mail", "Post TestMail");
//sender.start();
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
}
ManifestFile:
<?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>
错误:
07-31 07:23:40.927: E/SendMail(13132): null
07-31 07:23:40.927: E/SendMail(13132): java.lang.NullPointerException
07-31 07:23:40.927: E/SendMail(13132): at com.api.posttestcases.MainActivity.sendGmail(MainActivity.java:80)
07-31 07:23:40.927: E/SendMail(13132): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 07:23:40.927: E/SendMail(13132): at java.lang.reflect.Method.invoke(Method.java:515)
07-31 07:23:40.927: E/SendMail(13132): at android.view.View$1.onClick(View.java:3818)
07-31 07:23:40.927: E/SendMail(13132): at android.view.View.performClick(View.java:4438)
07-31 07:23:40.927: E/SendMail(13132): at android.view.View$PerformClick.run(View.java:18422)
07-31 07:23:40.927: E/SendMail(13132): at android.os.Handler.handleCallback(Handler.java:733)
07-31 07:23:40.927: E/SendMail(13132): at android.os.Handler.dispatchMessage(Handler.java:95)
07-31 07:23:40.927: E/SendMail(13132): at android.os.Looper.loop(Looper.java:136)
07-31 07:23:40.927: E/SendMail(13132): at android.app.ActivityThread.main(ActivityThread.java:5050)
07-31 07:23:40.927: E/SendMail(13132): at java.lang.reflect.Method.invokeNative(Native Method)
07-31 07:23:40.927: E/SendMail(13132): at java.lang.reflect.Method.invoke(Method.java:515)
07-31 07:23:40.927: E/SendMail(13132): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:780)
07-31 07:23:40.927: E/SendMail(13132): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596)
07-31 07:23:40.927: E/SendMail(13132): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
编辑:
首先。实例化发件人变量!
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() { }
主要答案:
我瘦你的错误可能在AsyncTask中。我用评论编辑了代码。
@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;
}