Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 469
Sako73 Avatar asked Oct 12 '10 20:10

Sako73


People also ask

What is startActivity ()?

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.

Can context be cast to activity?

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 .

How do I use intent to launch a new activity?

Intent in = new Intent(getApplicationContext(),SecondaryScreen. class); startActivity(in); This is an explicit intent to start secondscreen activity.


2 Answers

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.

like image 168
Alex Volovoy Avatar answered Sep 18 '22 08:09

Alex Volovoy


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.

like image 20
Bruno Bieri Avatar answered Sep 18 '22 08:09

Bruno Bieri