[FIXED] How can a class reference a variable from its containing composite class's parent class (which extends Activity)?

Issue

How can I get the value of “somevariable” from the “OtherClass”? Can/Should I use the Activity’s context for this as I was trying below?

public class ParentActivity extends Activity {
  //This variable is reused by multiple Activities inheriting form this class
  protected static String somevariable = "text";   
  ...
}

public class MyActivity extends ParentActivity {
  @Override
  public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  myObject = new OtherClass(this);
  myObject.doSomething();
  ...
  }

...
}

public class OtherClass(){
  private Context c;
  private String b;

  OtherClass(Context context) {
    c = context;
  }

    doSomething() {
        // This does NOT work. 
        // How can I get somevariable from the ParentActivity????
        b = c.somevariable;   
    }
}

Solution

If you want to access the specific somevariable defined in class ParentActivity then you should try to access it as ParentActivity.somevariable since it is declared static:

public class OtherClass { // Why were there extra parentheses ()
  private Context c;
  private String b;

  OtherClass(Context context) {
    c = context;
  }

  doSomething(){
  b = ParentActivity.somevariable; // Try this at home ;)
  }

}

Answered By – toe

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published