0

The code runs and my emails send, but anytime I check a box the subject is not altered because the method setSubject() is not called. Got it. Where I'm having trouble is where would I call/place this method so I can use the subject in my doInBackground() method. If I try calling setSubject() right before or anywhere in doInBackground I get an error for running concurrent tasks on the same thread. I tried calling setSubject() in a onPreExecute() block and still got the error. Anybody have any ideas? Here is the code and LogCat.

public class lastpage extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lastpage);


}

//method to verify email format using regex pattern
public boolean validateEmail(String email) { 
    Pattern pattern;
    Matcher matcher;
    //set variable to regex email pattern
    final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    pattern = Pattern.compile(EMAIL_PATTERN);
    matcher = pattern.matcher(email);
    if (matcher.matches()) {
        return true;
    }
    return false;

}


 public void sendEmails() {

 AsyncTask<String, Void, Void> myTask = new AsyncTask<String, Void, Void>() {
       private String sub = "Maintenance Request";
           String s = "";
        CheckBox main = (CheckBox) findViewById(R.id.checkBox1);
        CheckBox kitchen = (CheckBox) findViewById(R.id.checkBox2);
        CheckBox bathroom = (CheckBox) findViewById(R.id.checkBox3);
        CheckBox other = (CheckBox) findViewById(R.id.checkBox4); 

     public String setSubject(String subject) {
        sub = subject;
        if (main.isChecked()) subject = subject + " - Main Room";
        if (kitchen.isChecked()) subject = subject + " - Kitchen";
        if (bathroom.isChecked()) subject = subject + " - Bathroom";
        if (other.isChecked()) subject = subject + " - Other";
           return subject;
     }

              s = setSubject(sub); 
        protected Void doInBackground(String... params) {

    String host = "smtp.gmail.com";
    String username = "user@gmail.com";
    String password = "pwd";
    Properties props = new Properties();
    props.put("mail.smtp.ssl.enable", "true");
    Session session = Session.getInstance(props);

     session.setDebug(true);
      EditText e = (EditText) findViewById(R.id.enterEmail);
      EditText g = (EditText) findViewById(R.id.whichApt);

      String f = e.toString().replace("\\s", "");
      String to = "to@yahoo.com";
      String manager = "manager@gmail.com";
      String subject1 = "Maintenance Confirmation";


      MimeMessage msg = new MimeMessage(session);
      MimeMessage msg1 = new MimeMessage(session);


         try {

           msg.setFrom(new InternetAddress(username));
           msg1.setFrom(new InternetAddress(username));
           msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(to));
           msg1.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(manager));
           msg.setSubject(subject1);
           msg1.setSubject(s);
           msg.setText("Some really important stuff. Confirmed.");
           msg1.setText("Really important stuff needs attention");
           props.put("mail.smtps.auth", "true");
           props.put("mail.smtp.quitwait", "false");
           Transport t = session.getTransport("smtps");
           try {
               t.connect(host, username, password);
               t.sendMessage(msg, msg.getAllRecipients());
               t.sendMessage(msg1, msg1.getAllRecipients());
           }
           finally {
               t.close();
         } }  
         catch(Exception exc){
             exc.printStackTrace();
         }
        return null;
         }};

         myTask.execute(); }

//method to run when button is clicked
public void buttonclick3(View v) {
    //first extract text for EditText and convert to String
    EditText e = (EditText) findViewById(R.id.enterEmail);
    String email = e.getText().toString();
    //run validateEmail on String and show alert if format is invalid
    if (validateEmail(email) == false) {
         AlertDialog.Builder builder = new AlertDialog.Builder(this);
         builder.setMessage("Please enter a valid Email address.");
         builder.setTitle("Invalid Input!");
         builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {

               @Override
            public void onClick(DialogInterface dialog, int id) {
                   dialog.dismiss();
               }
           });
     builder.show();
    }
    else {

        sendEmails();
    }

    }
    }

Here is the LogCat I get when I try calling setSubject() anywhere.

 - 04-14 17:52:09.091: W/dalvikvm(1510): threadid=1: thread exiting with
   uncaught exception (group=0x41bbaa08)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): FATAL EXCEPTION: main
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): java.lang.IllegalStateException: Could not execute method of the activity
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$1.onClick(View.java:3626)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View.performClick(View.java:4231)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$PerformClick.run(View.java:17537)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Handler.handleCallback(Handler.java:725)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Handler.dispatchMessage(Handler.java:92)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.os.Looper.loop(Looper.java:158)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.app.ActivityThread.main(ActivityThread.java:5751)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invokeNative(Native Method)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invoke(Method.java:511)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at dalvik.system.NativeStart.main(Native Method)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): Caused by: java.lang.reflect.InvocationTargetException
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invokeNative(Native Method)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at java.lang.reflect.Method.invoke(Method.java:511)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at android.view.View$1.onClick(View.java:3621)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510):  ... 11 more
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): Caused by: java.lang.NullPointerException
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage$1.setSubject(lastpage.java:81)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage$1.<init>(lastpage.java:87)
 - 04-14 17:52:09.101: E/AndroidRuntime(1510): at com.example.maintenanceapp.lastpage.sendEmails(lastpage.java:72)
STLCards77
  • 121
  • 14
  • this code does not go with this error. you don't call that `setSubject` method. Please at least code consistent code/error log. (also, format the error and indicate which line is which) – njzk2 Apr 15 '14 at 01:06
  • This is the code that causes the error. Right above doInBackground. – STLCards77 Apr 15 '14 at 01:12
  • You have a NullPointerException on line 81 in setSubject(): may be it is `main.isChecked()`? – naXa stands with Ukraine Apr 15 '14 at 01:14
  • Yes that is exactly where the issue is occurring but my question is why? If it's not checked do not change the subject and if it is append it. Why am I getting an exception instead? – STLCards77 Apr 15 '14 at 01:20
  • Ok, how would error change if you move checkboxes initialization code into setSubject()? – naXa stands with Ukraine Apr 15 '14 at 01:20
  • I get the exact same error – STLCards77 Apr 15 '14 at 01:24
  • I suppose you get the 'error for running concurrent tasks on the same thread' because of this block with initializing checkboxes. Try to restructure a bit your workflow: find which checkbox is checked inside `buttonclick3()` method and then pass this value to `sendEmails()` and use within `AsyncTask`. – naXa stands with Ukraine Apr 15 '14 at 01:33
  • (the general idea is **to keep the UI code** on UI thread **separate from the functional code** on background thread) – naXa stands with Ukraine Apr 15 '14 at 01:39
  • No matter where I put it I get the exception. I tried taking the method setSubject() out of AsyncTask and then did String s = setSubject() as the first thing on buttonClick3. I also moved the whole method itself without the heading to set the variable itself in buttonClick3 and then do sendEmails(subject) as you suggested but I STILL GET THE ERROR. Have been stuck here for quite some time. – STLCards77 Apr 15 '14 at 01:57
  • I have no idea how I can code it with if statements, call it, then run it in a method and it is null. That makes absolutely no sense to me if I'm starting with something and the only thing I can do is add to it. – STLCards77 Apr 15 '14 at 01:58
  • Sorry, I don't know too... If NullPointerException persists, check [here](http://stackoverflow.com/questions/3264610/findviewbyid-returns-null) and [here](http://stackoverflow.com/questions/17378431/android-findviewbyid-returns-null), may be this will help. – naXa stands with Ukraine Apr 15 '14 at 02:15
  • I still haven't solved the issue, but I did find that it is related to the CheckBoxes being on a previous page. That is why when I look for them on my current activity they are null. I'm trying to find a way to reference the pieces from the previous page. If you have any thoughts on this feel free. Thanks for your time earlier. I appreciate your help. – STLCards77 Apr 15 '14 at 02:45

1 Answers1

1

Don't try to find checkboxes on a different activity. Instead, send the information needed in the Intent used to start the next activity.

nasch
  • 5,330
  • 6
  • 31
  • 52