Search code examples
androidandroid-activityandroid-context

Calling startActivity() from outside of an Activity context


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?


Solution

  • 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.