Reputation: 212
I have an activity "Results" which does some calculations, and a button for the user to send an email containing those results. I have made a class called "Sender" to accomplish this, but startActivity isn't working in my Sender class. I know the actual intent works, because I could get it to work inside of my Results activity, just not in the Sender class.
public class Results extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button sendEmail = (Button) findViewById(R.id.resultsEMAIL);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sender sender = new Sender();
sender.sendEmail();
}
});
///////
public class Sender{
public void sendEmail(){
Intent sendEmail = new
Intent(Intent.ACTION_SEND_MULTIPLE);
ArrayList<Uri>uris = new ArrayList<Uri>();
uri.add(someUri);
uri.add(otherUri);
sendEmail.setType("message/rfc822");
sendEmail.putExtra(Intent.EXTRA_EMAIL, allEmails);
sendEmail.putExtra(Intent.EXTRA_SUBJECT, "Subject");
sendEmail.putExtra(Intent.EXTRA_TEXT, results);
sendEmail.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
try {
startActivity(Intent.createChooser(sendEmail, "Send")); }
catch
(android.content.ActivityNotFoundException ex)
{ Toast.makeText(context, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); }
}
I have tried passing the context from Results
Results.context.startActivity(Intent.createChooser(SendEmail,"Send"));
And I have also tried
sendEmail.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Regardless of what I do, I get the exception
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
Should I just abandon trying to do this in a separate class?? I wanted to make a Sender class to clean up Results.
Upvotes: 1
Views: 428
Reputation: 2403
You need to pass Context of the activity to sendMail() method.
public class Results extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button sendEmail = (Button) findViewById(R.id.resultsEMAIL);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Sender sender = new Sender();
sender.sendEmail(Results.this);
}
});
And in your sendMail() method use context to start activity.
public void sendEmail(Context context){
Intent sendEmail = new Intent(Intent.ACTION_SEND_MULTIPLE);
//set data to intent
context.startActivity(Intent.createChooser(sendEmail, "Send"));
}
Upvotes: 1