Calling startActivity() from outside of an Activity context

Sako73 picture Sako73 · Oct 12, 2010 · Viewed 263.3k times · Source

I have implemented a ListView in my Android application. I bind to this ListView using a custom subclass of the ArrayAdapter class. Inside the overridden ArrayAdapter.getView(...) method, I assign an OnClickListener. In the onClick method of the OnClickListener, I want to launch a new activity. I get the exception:

Calling startActivity() from outside of an Activity  context requires the  
FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

How can I get the Context that the ListView(the current Activity) is working under?

Answer

Alex Volovoy picture Alex Volovoy · Oct 12, 2010

Either

  • cache the Context object via constructor in your adapter, or
  • get it from your view.

Or as a last resort,

  • add - FLAG_ACTIVITY_NEW_TASK flag to your intent:

_

myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Edit - i would avoid setting flags as it will interfere with normal flow of event and history stack.