0

I was wondering if someone could help me with debugging. I am currently using the code in:

Sending Email in Android using JavaMail API without using the default/built-in app

and have used all of the code as directed. After inputting my email fields, I was unable to get email to be sent. I noticed a piece of code in GMailSender.java, where it seemed that there was a missing piece of code.

}catch(Exception e){

}

Knowing that I had debugged every other part of the code, I added a Log.e, as so.

}catch(Exception e){
    Log.e("GmailDebug", e.getMessage(), e); 
}

As a result, I noticed that I got the following logs.

01-16 22:22:38.933: E/GmailDebug(4487): null
01-16 22:22:38.933: E/GmailDebug(4487): android.os.NetworkOnMainThreadException

After commenting out the lines beforehand and systematically uncommenting them, I finally was able to determine that I didn't get any logs until I uncommented the line

Transport.send(message);

Can someone help me out, and tell me how I can prevent these errors? Thanks!

Community
  • 1
  • 1
The Obscure Question
  • 1,134
  • 11
  • 26

1 Answers1

1

This happens because you are doing a network operation on the main thread, and this is not allowed on Android 3.0 and above. Even though it is in a service, services are run on the UI thread unless you specifically launch them in another thread or create a thread inside it.

You can fix this by running the task in a background thread off the main UI thread, by using a Thread or an AsyncTask.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
  • I can understand how this corrects android.os.NetworkOnMainThreadException, but will it rectify the null log? – The Obscure Question Jan 17 '13 at 07:18
  • @TheObscureQuestion It may, depending on whether or not your value is sourced from the internet. If your value is assigned from or during the networking operation, then it should rectify it. – Raghav Sood Jan 17 '13 at 07:20
  • Alright. Looking back at the original thread, (http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-built-in-a), would I put the GMailSender.java in an AsyncTask, or MailSenderActivity.java? I would think the former, as it does not interact with the UI. – The Obscure Question Jan 17 '13 at 07:28
  • Yeah, you should convert `GMailSender` into an AsyncTask. – Raghav Sood Jan 17 '13 at 07:29
  • In that case, where would I define it, as GMailSender is already defined with `public class GMailSender extends javax.mail.Authenticator` – The Obscure Question Jan 17 '13 at 07:32
  • @TheObscureQuestion I can't really answer that in a comment. [Here's](http://www.vogella.com/articles/AndroidPerformance/article.html) an excellent tutorial on using AsyncTasks. – Raghav Sood Jan 17 '13 at 07:35