Nadeem
Nadeem

Reputation: 227

Start a new Activity from non Activity class

I want to start a new activity in non-Activity class that implements a DialogListener following is my code:

public class FacebookLoginDialog implements DialogListener {
  @Override
  public void onComplete(Bundle values) {
    HomeActivity.showInLog(values.toString());

    Intent i1 = new Intent (this, SearchActivity.class);
    startActivity(i1);
  }

  @Override
  public void onFacebookError(FacebookError e) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onError(DialogError e) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onCancel() {
    // TODO Auto-generated method stub
  }
}

I can't start the new activity using intent in onComplete method, please help.

Thanks

Upvotes: 19

Views: 30689

Answers (4)

钟智强
钟智强

Reputation: 480

For Easy Usage you can a method for this particular method:

public class Something
{
   public static void navigate(Context context,  Class<?> nameOfClass)
    {
        Intent i = new Intent(context, nameOfClass);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

can be called in other class and method everytime by calling this:

Something.navigate(activityName.this, classYourWantTONavigateTo.class);

Upvotes: -1

passionatedevops
passionatedevops

Reputation: 533

use starActivity from non-activity class:

Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "YOUR STRING");
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Share via...");
        context.startActivity(Intent.createChooser(intent, "Share"));

Upvotes: 1

Malcolm
Malcolm

Reputation: 41498

This doesn't work because you need a Context in order to start a new activity. You can reorganize your class into something like this:

public class FacebookLoginDialog implements DialogListener {
  private final Context context;

  public FacebookLoginDialog(Context context) {
    this.context = context;
  }

  @Override
  public void onComplete(Bundle values) {
    HomeActivity.showInLog(values.toString());

    Intent i1 = new Intent (context, SearchActivity.class);
    context.startActivity(i1);
  }

  //Other methods...
}

Then it will work.

Upvotes: 30

Peter Moskala
Peter Moskala

Reputation: 360

Pass context as constructor parameter and then try this

Intent i = new Intent(this, SearchActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

Upvotes: 13

Related Questions