In the above video you will find – Solving Calling startActivity() from outside of an Activity context issue.
While trying to open a browser intent (webpage), when clicking an item in the recycler view of my test app, I faced the following exception:
Calling startActivity() from outside of an Activity context ...
In the video above I provide you with the line of the code that solved the problem in this particular case.
The video shows the part of the code that generates the exception. Basically, I was trying to open a new web page when clicking one particular item in the Recycler View of my Android application.
I try to open the web page by creating a new intent and using the Intent.ACTION_VIEW flag. Then in the context (using the mContext variable), I call the startActivity method, and pass the new Intent variable.
When running the application it crashes and gives me the “Application keeps stopping” dialog box.
So basically, in the video above you will see how to solve the “Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag” issue in Android Studio.
The above is an Android Runtime Exception and it is raised when trying to load a browser intent from a Recycler View.
To fix the error, you will need to add the following line, in between the Intent creation line and the line that calls the startActivity method:
The FLAG_ACTIVITY_NEW_TASK flag, clears the error and you can load the web page successfully:
So, after you apply the line above, you will see that the web page or the browser intent will load correctly and the app won’t crash anymore.
This solution worked on this particular case, but might not be suitable in different situation.
The above flag is required in these particular situation, like the case when loading a new web page from Recycler View.
Leave your questions and comments in the section below.