Hello. I have a snippet and a button. How do I correctly call the sendMail() method when I click a button? And why the Mail instance creation is highlighted (Unreachable statment)?

Here is the code:

 public class TabFragment1 extends Fragment { private Mail m ; private ImageButton imgSend; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.tab_fragment_1, container, false); m = new Mail("********@gmail.com", "*******"); } public void sendEmail(View view){ String[] toArr = {"toemail1@domain1.tld"}; // This is an array, you can add more emails, just separate them with a coma m.setTo(toArr); // load array to setTo function m.setFrom("fromEmail@domain.tld"); // who is sending the email m.setSubject("subject"); m.setBody("your message goes here"); try { m.addAttachment("/sdcard/myPicture.jpg"); // path to file you want to attach if(m.send()) { // success Toast.makeText(getActivity(), "Email was sent successfully.", Toast.LENGTH_LONG).show(); } else { // failure Toast.makeText(getActivity() ,"Email was not sent.", Toast.LENGTH_LONG).show(); } } catch(Exception e) { // some other problem Toast.makeText(getActivity(), "There was a problem sending the email.", Toast.LENGTH_LONG).show(); } } 
  • Anything after the return will never be executed. So put everything after return before it. - Yuriy SPb
  • This is a carelessness, but with a call to the sendMail method, it cares more (in the activity of the norm plows) ?? - Dmitriy Dev
  • Why not put the button in the fragment itself, and not in the activation? .. - Yuriy SPb
  • one
    Do you have a listener, is it indicated through the markup? .. If so, don’t do so. Do not. Assign it programmatically. - Yuriy SPb
  • one
    Never place listeners in the markup. Never in my life. The Google engineer who invented it needs to be burned at the stake. - Vladyslav Matviienko

1 answer 1

The android:onClick in the markup works only for listeners pressing the button in the activation, for the fragment you need to install the listener programmatically. On several ways to assign a listener programmatically read this question.

Unreachable statment is an unreachable declaration, the code behind the return statement will not be executed, as the method will exit.