terriblesarcasm
terriblesarcasm

Reputation: 33

Starting Activity in AsyncTask passing context from activity

Here is the AsyncTask constructor:

private Context context;
private MainActivity activity;
public databaseTask(MainActivity activity, String task, String username, String password) {
    super();
    this.activity = activity;
    this.context = this.activity.getApplicationContext(); 

And here is the call in MainActivity:

databaseTask dbGetGroupsTask = new databaseTask(MainActivity.this, "login", username, password);
dbGetGroupsTask.execute(username);

In the onPostExecute I have this code:

Intent s = new Intent(context, userLandingPage.class);
Bundle b = new Bundle();
b.putString("userName", username);
s.putExtras(b);
context.startActivity(s);

The error I am getting at runtime is: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

From all the replies in previous questions I have seen it says in order to start an activity from outside the activity without setting a flag (as setting the flag is not recommended) you need to have the context of the activity. I thought this was what I was doing so I am not sure why this not working.

Upvotes: 1

Views: 3408

Answers (1)

Blackbelt
Blackbelt

Reputation: 157457

Since one of the argument of your AsyncTask is the activity you can directly use

Intent s = new Intent(activity, userLandingPage.class);
activity.startActivity(s);

Upvotes: 1

Related Questions