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:

...
public class MainActivity extends Activity {
  private static MainActivity instance;
  private static void setInstance (MainActivity instance) {
    MainActivity.instance = instance;
  }
  public static MainActivity getInstance () {
    return instance;
  }
  public void somePublicMethod () {
  ...
  }
  public void onCreate (Bundle savedInstanceState) {
    super.onCreate (savedInstanceState);
    setContentView (R.layout.activity_main);
    setInstance (this);
    ...
  }
  ...
}

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.

No comments:

Post a Comment