-3

I am getting java.lang.NullPointerException error during executing the code, I am not able to figure it out what is missing . Can any one point the mistake ? For me looks fine these code but still send mail function is returning NUll :(

Code :

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


}

Main Activity :

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>

error:

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)
user3688062
  • 53
  • 1
  • 11
  • Where is `sendGmail()`?? I can not see. – Pankaj Kumar Jul 31 '14 at 07:40
  • The NPE is in MainActivity. Are you declaring a `GmailSender` object, but not initializing it? – Mike M. Jul 31 '14 at 07:41
  • Could you post the sendGmail method from MainActivity too? The Mail sending method looks ok. – skipper3k Jul 31 '14 at 07:41
  • and which line is line 80 in `MainActivity.java`? – Unihedron Jul 31 '14 at 07:50
  • I have added my MainActivity code also – user3688062 Jul 31 '14 at 07:50
  • 2
    Yep. `sender` is null. – Mike M. Jul 31 '14 at 07:51
  • @ Mike M But i am using sender.sendMail("abc@gmail.com", "Test Mail", "Post TestMail"); then why is it sending null value :( – user3688062 Jul 31 '14 at 07:54
  • 2
    @user3688062 You're invoking a method on a `null` field. That's what the `NullPointerException` is thrown for. This could have been spotted and resolved if you ran debuggers. Please also see http://sscce.org/ on advice on how to format a "Short, Self Contained, Correct (Compilable), Example" useful to a question - your code is not __formatted__, __commented__ and __explained__, it's hard to help if not for the easily found mistake. – Unihedron Jul 31 '14 at 07:54
  • possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – Mark Rotteveel Jul 31 '14 at 09:58

1 Answers1

1

Edit:

First. Instantiate the sender variable!

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

Add the constructor to GmailSender class

public GmailSender() { }

Primary answer:

I thin your error could be in the AsyncTask. I edited the code with comments.

@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;
}
skipper3k
  • 171
  • 1
  • 1
  • 8