Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

How to return to MainActivity

I have an android app in which I want to send an email and after the email is sent I want it to return to MainActivity. I already asked the question, but couldn't figure it out completely. The person said I should startActivityForResult() which I did but the same problem persists. Here is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_form);

    ((Button) findViewById(R.id.btnOK)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            sendEmail();
        }
    });
}


private int Send_Email_Request = 1;

private void sendEmail() {
    String to = ((EditText) findViewById(R.id.txtTo)).getText().toString();
    String number = ((EditText) findViewById(R.id.phoneNumber)).getText().toString();
    String mess = ((EditText) findViewById(R.id.txtMessage)).getText().toString();
    Intent mail = new Intent(Intent.ACTION_SEND);
    mail.putExtra(Intent.EXTRA_EMAIL, new String[]{to});
    mail.putExtra(Intent.EXTRA_SUBJECT, number);
    mail.putExtra(Intent.EXTRA_TEXT, mess);
    mail.setType("message/rfc822");
    startActivityForResult(mail, Send_Email_Request);
}

Anyone got any ideas? By the way I'm sorry it cut off my code. I've tried to fix it several times but to no avail.

Seth Kroger
Seth Kroger
56,413 Points

I fixed the formatting of your code. to format code blocks you need to enclose it with 3 back-ticks (```)on the lines before an after. See the Markdown Cheatsheet linked the edit box for details.

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

When you use startAcivityForResult() you need to override/provide onActivityResult() in your Activity to receive the result back.

Yes this was what I thought I should do. So where would I put this and how would I set it up so that after I send an email I return to the MainActivity and restart the app?