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?
Starting activities or services. To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent.
The Best Answer is getApplicationContext(); Wherever you are passing it pass this or ActivityName. this instead. you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity .
Intent in = new Intent(getApplicationContext(),SecondaryScreen. class); startActivity(in); This is an explicit intent to start secondscreen activity.
Either
Or as a last resort,
_
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.
You can achieve it with addFlags instead of setFlags
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
According to the documentation it does:
Add additional flags to the intent (or with existing flags value).
EDIT
Be careful when you are using flags that you may change the history stack as Alex Volovoy's answer says:
...avoid setting flags as it will interfere with normal flow of event and history stack.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With