简体   繁体   中英

NullPointerException when getting String from another activity

I'm creating a Mail client with javamail. I've set a login activity which stores mail and password. I have the code which sends the mail in a class called Data.java. The problem is that I can't get SharedPreferences from there becouse it is not an Activity and it doesn't extend PreferenceActivity. I've needed to use Looper.prepare() becouse otherwise it threw another exception. I'm trying to get Shared Prefs from MainActivity but I get a NullPointerException when I try to print it. My MainActivity code:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences prefs = getSharedPreferences("loginPrefs", Context.MODE_PRIVATE);
        mail1 = prefs.getString("email", null);
        pass = prefs.getString("pass", null);

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }

    public String getMail1(){
        return mail1;
    }
    public String getPass(){
        return pass;
    }

Data.java code:

public class Data{

    String a;
    String b;

    private void getEverything(){
        Looper.prepare();
        MainActivity d = new MainActivity();
        a = d.getMail1();
        b = d.getPass();
    }


    public void sendMail(){
        getEverything();
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(a, b);
                    }
                });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(a));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(gmail.to));
            message.setSubject(gmail.subject);
            message.setText(gmail.text);

            Transport.send(message);
            System.out.println(a);
            System.out.println(b);
            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

logcat:

java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:856)
     Caused by: java.lang.NullPointerException
            at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
            at com.test.email.Data.sendMail(Data.java:61)
            at com.test.email.gmail.doInBackground(gmail.java:40)
            at com.test.email.gmail.doInBackground(gmail.java:19)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:856)
System.out.println(a);
System.out.println(b);

a and b are null . That's the reason for NPE.

The reason they are null :

MainActivity d = new MainActivity();

Never instantiate activities with new . (Use Intent instead. But you don't need to instantiate an activity here.)

So the activity object you get here is not the same activity you've set the variable values in.

Instead, pass whatever values you need in the Data class as method parameters, like

public void sendMail(String email, String password) { ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM