Search code examples
androidinheritanceandroid-activitycomposition

Composition with android.app.Activity


The source of wisdom "Effective Java 2nd" says "Favor composition over inheritance" (item 16). Now when it comes to Android Activities, it's simple to extends from one but you break encapsulation and the code may break when the superclass is modified. I tried to compose . Here is the code of the component Activity:

public class SimpleActivity extends Activity{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textview = new TextView(this);
        textview.setText("This is the Artists tab");
        setContentView(textview);
    }   
}

Here is the composed. For each Activity's lifecycle methods, I call the forward methods.

public class ComposedActivity extends Activity {
    private SimpleActivity act;
    public ComposedActivity(){
        act = new SimpleActivity();
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        act.onCreate(savedInstanceState);
    }   
}

But the app keeps crashing caused by: java.lang.NullPointerException. What am I doing wrong ? Just asking out of curiosity. What do you recommend to expand an Activity without inheritance ?


Solution

  • You can't really have an activity inside another activity. If you want to use composition for Android components, have a look at fragments.

    You can use composition without using fragments simply by factoring your logic into plain Java classes (POJOs) that are not Android components. If they need access to an activity, you can pass a references to the target activity in the constructor. Or better yet, have your activities implement some interface have them hold a reference to it, not to concrete activities.