Issue
I need to fetch the MainActivity context and call getIntent() to process the intent that started the Activity.
Due to some reasons, I don't want to do this in my MainActivity (that would have been a simple getIntent() in any non-static method of the class).
The MainActivity's instance will be exposed (somehow) and with that object, I need to invoke getIntent().
There's the following way:
public class MainActivity extends Activity {
// Store the activity context
private static Activity activityContext;
public void onCreate() {
activityContext = this;
}
public static Activity getActivityContext () {
return activityContext;
}
}
But is there any other way to get the MainActivity context? Like a direct func to the Activity's instance instead of capturing the instance and exposing a method as shown above..
Solution
Retrieve the Intent
in onCreate
, pull everything you need out of it and then you can store it in a number of places.
SharedPreferences
or a Database
or Static Variables
or a Singleton
When you finally need the Intent
data you can pull it from a place that is more permanent, instead of an Activity
which is not.
Answered By - avalerio
Answer Checked By - David Goodson (JavaFixing Volunteer)