Sunday, June 26, 2016

Android Development - Access Activity Instances from Other Classes

Each page on Android app is defined by an activity instance or an object. Sometimes, you may want to edit the instance externally, i.e., from other objects or classes. The following code shows how to do access the instance of MainActivity class externally:

As you can see from the code above, static variable instance is to be assigned in the onCreate method. Now, this instance can be accessed externally by calling the public getInstance method, as shown below:...public class SomeClass { public void someMethod () { MainActivity.getInstance().somePublicMethod(); }}

This method is called singleton design, as there is only one instance of the Activity class, which we want to access externally.