Get Activity Instance
Solution 1:
Here is a way to avoid memory leaks using static variable: make static weak reference to Activity instance that will be set in onCreate(Bundle) method.
Write in your secondary class something like below:
publicClassSecondClass{ privatestaticWeakReference<Activity> mActivityRef; publicstaticvoid updateActivity(Activity activity) { mActivityRef = newWeakReference<Activity>(activity); }
Then in onCreate(Bundle) method of your Activity class:
@Override onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SecondClass.updateActivity(this); ... }
Use activity instance this way:
mActivityRef.get()
Solution 2:
Activitya= (Activity) getContext();
As long as you pass the current activity as a context in the constructor, as you are already doing.
Solution 3:
I just set a variable in my main activity like so... public static Activity activity = this;
then I can reference it from anywhere using: MainActivity.activity
.
You can also set it in the onCreate() method, just set up the variable at the top of your main activity class like this public static Activity activity;
then in the onCreate() method just add activity = this;
anywhere.
This will work for any class that extends Activity, for example public class MainActivity extends Activity
however you can call the variable from any class even if they don't extend Activity.
Hope this helps.
Solution 4:
Method this.getParent()
works.
Post a Comment for "Get Activity Instance"